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
}
}
In android, by pressing a back button or home button. So put an event key listener for back & home button and terminate the service.
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.
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
.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With