How to detect an application removed from a recent list?

I am working on a music application, and I want to stop the service when the user removes the application from the recent list, and not when the first action is destroyed (because when the user clicks back until the application minimizes, in this case the activity is also destroyed first). Please, help.

+13
source share
2 answers

I want to stop the service when the user removes the application from the recent list.

Yes, you can do this using the stopWithTask flag as true for the service in the manifest file.

Example:

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

OR

If you need to remove an event from a recent list and do something before the service stops, you can use this:

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

Thus, your onTaskRemoved service method will be called. (Remember that it will not be called if you set stopWithTask to true ).

 public class MyService extends Service { @Override public void onStartService() { //your code } @Override public void onTaskRemoved(Intent rootIntent) { System.out.println("onTaskRemoved called"); super.onTaskRemoved(rootIntent); //do something you want //stop service this.stopSelf(); } } 

Hope this helps.

+34
source

I am posting this answer since the one chosen as the best solution does not work for me.

This is an updated version:

First create this class of service:

  public class ExitService extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onTaskRemoved(Intent rootIntent) { System.out.println("onTaskRemoved called"); super.onTaskRemoved(rootIntent); //do something you want before app closes. //stop service this.stopSelf(); } } 

Then declare your service this way in the manifest label:

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

Now just start the service where you want to do something before closing the application.

  Intent intent = new Intent(this, ExitService.class); startService(intent); 
0
source

Source: https://habr.com/ru/post/1209198/


All Articles