0

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:

  1. How to stop the service when the application is killed from recent apps list?
  2. 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?

  • You don't need a foreground service at all if you don't want it to run after app killed. Also you may want to create a service connection to your activity, and once activity gets killed, service will stop too – Vladyslav Matviienko Jun 01 '18 at 11:42
  • Thank you for the reply. How can I create a connection between activity and service? I am calling the stopForegroundService() method from onDestroy function of the activity. – Nimesh Chandramaniya Jun 01 '18 at 11:54

1 Answers1

0

As if some thread is still not properly killed ?

UPDATE
Try to add this attribute stopWithTask="true"in the manifest file

<service
android:enabled="true"
android:name=".ExampleService"
android:exported="false"
android:stopWithTask="true" />

Please refer to this answer. Hope that helps
https://stackoverflow.com/a/53334788/10069542

MMasmoudi
  • 508
  • 1
  • 5
  • 19
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. [how to answer](https://stackoverflow.com/help/how-to-answer) – Agilanbu Dec 06 '18 at 10:26
  • My apologies for this. Now I updated my answer. Thank you – MMasmoudi Dec 06 '18 at 10:41