Android: OnDestroy isn't called when I close the app from the recent apps button

2022-09-01 13:11:32

When we press this button

We see the apps which we didn't close, like this

But when we want to close an app from this screen (below image), the method onDestroy() isn't called, however the app is closed. I need to call onDestroy() when the app is closed in this way. How can I do this?


答案 1

As specified in the Android documentation, it is not guaranteed that will be called when exiting your application.onDestroy()

"There are situations where the system will simply kill the activity's hosting process without calling this method"

https://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29

Instead, you can create a service which will be notified when the Task your activities are running inside is destroyed.

Create the service class:

public class ClosingService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);

        // Handle application closing
        fireClosingNotification();

        // Destroy the service
        stopSelf();
    }
}

Declare / register your service in the manifest (within the application tag, but outside any activity tags):

<service android:name=".services.ClosingService"
             android:stopWithTask="false"/>

Specifying will cause the method to be triggered in your service when the task is removed from the Process.stopWithTask="false"onTaskRemoved()

Here you can run your closing application logic, before calling to destroy the Service.stopSelf()


答案 2

You should read some info about Activity lifecycle. There is one thing about onDestroy method, it doesn't get called all time. You mustn't rely on it.

Specify please what are you trying to achive and I'll try to offer better solution.

Suggestion

So, if I understood you right, I can suggest one thing. Start a that will fire every N seconds (it's not really heavy to system). Register and for this broadcast in . This way you'll get or depending on if there is any that can catch your . And if no receivers than check for some value that indicates if was pressed.ServiceLocalBroadcastBroadcastReceiverActivitiestruefalseBroadcastReceiverLocalBroadcastSharedPreferencesButton


推荐