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

15,341

Solution 1

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.

Solution 2

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()

Share:
15,341
fergaral
Author by

fergaral

18-year-old self-taught Android, Windows Phone and Web developer (or trying to :D)

Updated on July 31, 2022

Comments

  • fergaral
    fergaral almost 2 years

    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
    }
    
    }