Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}

}
like image 468
fergaral Avatar asked Apr 08 '15 17:04

fergaral


People also ask

How do I stop an android application from closing?

In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.

How do I keep my service alive android?

But in order to keep a service alive like playing a song in a background. You'll need to supply a Notification to the method which is displayed in the Notifications Bar in the Ongoing section. In this way the app will keep alive in background without any interuption.


2 Answers

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.

like image 177
Stan Avatar answered Oct 04 '22 08:10

Stan


in your service class @Override onStartCommand method

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

To Kill a service itself, you can use stopSelf()

like image 31
Sai Phani Avatar answered Oct 04 '22 09:10

Sai Phani