fergaral fergaral - 2 months ago 29
Android Question

How to keep an IntentService running even when app is closed?

In my Android app I start an IntentService from within an Activity by calling

startService(new Intent(this, MyService.class));


And it works like a charm. I can move between Activies, press the Home button to switch to other apps... and it's still working. But if I remove my app from the recents screen, my service is stopped. How can I avoid this? In other words, how can I keep my service running even if my app is closed from recent apps?

My service code is as follows:

public class MyService extends IntentService {

public MyService() {
super("MyService");
}

@Override
protected void onHandleIntent(Intent intent) {
//Here I run a loop which takes some time to finish
}

}

Answer

IntentService is not running all the time but it works on Intent base. You send, lets say a command to do (do some job), using Intent and service executes that job and stops itself after that waiting for other Intent.
You should use usual Service instead of IntentService to achive your goal. Service should be configured as START_STICKY.