Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service is created again after onTaskRemoved

I made a remote service, this service is started by my activity the first time that boot, after that, the activity always look if the service is started to avoid start it again.

The service run some methods in the onCreate function. This service is running always and started on boot time also.

The problem (is not a big problem but I want to know why) is that once the service is created if I stop my activity the onTaskRemoved is called, this is correct, but after few seconds the oncreate method is called again and the service starts 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 the service is started if it was not running

like image 337
Marcel Avatar asked Feb 08 '13 11:02

Marcel


1 Answers

The problems is that you service is sticky per default, this means that it will be restarted when killed, until you explicitly ask for it to be stopped.

Override the onStartCommand() method in your service, and have it return START_NOT_STICKY. Then you service will not be restarted when killed.

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    return START_NOT_STICKY;
}
like image 145
Bjarke Freund-Hansen Avatar answered Oct 11 '22 12:10

Bjarke Freund-Hansen