Search code examples
androidserviceandroid-activityrestartshutdown

Android Service Stops When App Is Closed


I am starting a service from my main Android activity as follows:

final Context context = base.getApplicationContext();
final Intent intent = new Intent(context, MyService.class);
startService(intent);

When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?


Solution

  • I'm in the same situation, so far I learned that when the App is closed the Service gets closed as well, because they are in the same main-thread (aka process), so the service should be on another main-thread in order for it NOT to be closed, look into that and look into keeping the service alive with alarm-manager, here an example http://www.vogella.com/articles/AndroidServices/article.html this way your service won't be shown in notification.

    Lastly, after all the research I've done I'm coming to realize that the best choice for a long running service is startForeground() (which shows notification), because it is made for that and the system actually deals with your service well.

    Note that in case of a VpnService, startForeground is not required, because there is a built-in notification for VPNs.

    Update: said built-in notification got removed by google (now VpnService needs startForeground as well).