0

I am making an app in which when user exits the application some methods will run but i cannot do it on onDestroy method because sometimes it is not working and if it is working then only the first line is executed so how to run method when user presses back button or remove it from the recent apps?

2 Answers2

1

You can use Android Service to do that

Here is what you can do if its just about stopping service when application is killed by swiping from Recent app list.

Step 1: Inside your Manifest file, keep flag stopWithTask as false for Service. Like:

    <service
        android:name="com.myapp.MyService"
        android:stopWithTask="false" />

Step 2: Now in your MyService service, override method onTaskRemoved. (This will be fired only if stopWithTask is set to false).

public class MyService extends Service {

@Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        //Do whatever you want
    }
}
Anisuzzaman Babla
  • 6,510
  • 7
  • 36
  • 53
0

Just override this method in your activity that you are exiting from and do your task here:

@Override
public void onBackPressed() {
    // Do your exit task here
}
Asif Rahman
  • 171
  • 6
  • Yes i did it ...but what if the user do not press back button and just stop it without pressing back button. I mean like from background apps someone slide and stop the app – user10160402 Aug 13 '18 at 17:47
  • Then this might be the answer you were looking for: https://stackoverflow.com/a/26882533/9611198 – Asif Rahman Aug 13 '18 at 18:08
  • I already called same method in onbackpressed but i to run it in other situation also when user do not use back button . – user10160402 Aug 13 '18 at 18:09