I am working on an Android application in which I create a foreground service. Below is the code to kill the foreground service:
private void stopForegroundService()
{
Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");
if(downloadAsyncTask!=null) //to stop async task
downloadAsyncTask.cancel(true);
// Stop foreground service and remove the notification.
stopForeground(true);
// Stop the foreground service.
stopSelf();
}
I want to stop this service when the user kills the application from the "Recent apps" list. I have the methods onDestroy()
and onTaskRemoved()
in the service class. The stopForegroundService()
is called from these functions.
When the user kills the app from the recent apps list, the stopForegroundService()
method is called but the service keeps running. However, I am able to stop the service when the async task is complete.
I have following questions:
- How to stop the service when the application is killed from recent apps list?
- Is it possible that the service is getting killed but the async task continues to run? If yes, how to fix it?
I would appreciate any suggestions and thoughts on this topic. Thank you.
EDIT:
The method stopForegroundService()
is called, the foreground service notification is removed but the async task is not stopped. How to fix this?