Service is created again after onTaskRemoved

I made a remote service, this service is started by my activity at the first boot, after that the activity always looks if the service is started so as not to start it again.

The service runs some methods in the onCreate function. This service always works and also starts at boot.

The problem (not a big problem, but I want to know why) is that after creating the service, if I stop my activity, onTaskRemoved is called, that’s correct, but after a few seconds the oncreate method is called again and the service will start again.

Any idea why? And how can I control this?

<service
        android:name=".Service"
        android:icon="@drawable/ic_launcher"
        android:label="@string/service_name"
        android:process=":update_process" >
</service>

AndroidManifest.xml

if (!isRunning()) {
    Intent service = new Intent(this, UpdateService.class);
    startService(service);
} else {
    //Just to debug, comment it later
    Toast.makeText(this, "Service was running", Toast.LENGTH_SHORT).show();
}

When a service starts, if it was not started

+5
source share
2

, , , , , .

onStartCommand() START_NOT_STICKY. .

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    return START_NOT_STICKY;
}
+8

Bjarke , , , .

Android onStartCommand() , , ( ) .

intent onCreate(), null ( ), , Android , .

NON_STICKY , / , .

, STICKY, , - .

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    // intent is null only when the Service crashed previously
    if (intent == null) {
        cleanupAndStopServiceRightAway();
        return START_NOT_STICKY;
    }
    return START_STICKY;
}

private void cleanupAndStopServiceRightAway() {
        // Add your code here to cleanup the service

        // Add your code to perform any recovery required
        // for recovering from your previous crash

        // Request to stop the service right away at the end
        stopSelf();
}

( stopSelf()) onTaskRemoved(), Android .

+6

All Articles