How to avoid system killing service when application/activity is killed

Salivan picture Salivan · Apr 13, 2014 · Viewed 8.5k times · Source

I have an app with one activity and one service. If I kill the activity while the service is running it gets killed too. It is very important for me that the service doesn't get killed. How to make that when the system kills (or I kill it by clearing the "Recent apps" list) the activity the service still remains active until it finishes its job? Thanks in advance!

Answer

Sipka picture Sipka · Apr 13, 2014

You can try returning START_STICKY from onStartCommand in your Service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}