简体   繁体   中英

Acitivity onDestroy not always called

I'm developing a radio-streaming application and a homescreen widget. The problem is when I kill the application, I want to modify the image in the homescreen widget like this :

@Override
protected void onDestroy() {
    //update widget
    WidgetIntentReceiver.updateWidgetFromActivityDestroy(getApplicationContext());

    mMediaPlayer.reset();
    mMediaPlayer.release();
    mMediaPlayer = null;

    System.out.println("End onDestroy -> stop stream");

    super.onDestroy();
}

But the code to modify widget is not always called (the 'System.out.println' not appears). I have already read that onDestroy is not always called. But I don't find another solution ?

Thanks.

is when I kill the application . The keyword here is kill . By kill you mean force close of the application as I understood. If so then you have no way to change something. Because when you force close the application or even if the OS kill your app on some reason (memory limits, battery optimizations, etc.) - there is no way to do something because the entire application process (with your package name) is simply killed by something like Process.killProcess (int pid) without any callbacks. And onDestroy() behavior in such moments is completely undefined. And it is written in the documentation:

[..] There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the PROCESS GOES AWAY.

So don't forget that onDestroy() it is a method which is tightly bound to the Activity's lifecycle and not the whole application lifecycle. As a workaround you should create some Base Activity and in its OnPause() do the stuff you want and then make all other activities in your application inherit from it.

Other (bad solution which should not be used in production code) is to create a background Service which will in cycle check if your app is running with actvityManager.getRunningAppProcesses(); and modify the widget if not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM