Thiago
Thiago

Reputation: 13302

Make background service always run and never killself or system destroy it

Hello I am running a background service to check in my server if there is a new data.

But if I kill the App, the background service also dies. If I run the background service on it;s on process, the system kill it after it has run a couple times.

Manifest

<service
            android:name=".backgroundSerive"
            android:enabled="true"
            android:exported="false"/>

Option 2

<service
            android:name=".backgroundSerive"
android:process=":my_process"
            android:enabled="true"
            android:exported="false"/>

MainAActivity - Starting the service

Intent i = new Intent(this, backgroundSerive.class );
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startService(i);

Service

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
...start runnable
        return  START_STICKY; 
    }

I try both option, The service keeps getting killed.

Any advice. To make my server always run. thank you

Upvotes: 0

Views: 3248

Answers (2)

Deliganli
Deliganli

Reputation: 320

startForeground function sends the service to foreground, so android system considers this operation as a foreground task. Which is very less likely to be killed.

If you have choosen the services destroy action as START_STICKY it would get destroyed but right after it destroyed it should be reinitialized with a null intent.

You may consider using Alarm for such event. Since alarms are running in an internal process they reduce the app overhead, yet they provide recurring checks.

Upvotes: 1

Sipty
Sipty

Reputation: 1154

You need to call startForeground() from within the service, to lower the chance of Android actually killing it. Please check out this sample for an example implementation.

Upvotes: 1

Related Questions