不总是调用Activity onDestroy

时间:2013-07-28 15:28:25

标签: android android-activity

我正在开发一个无线电流应用程序和一个主屏幕小部件。 问题是当我终止应用程序时,我想修改主屏幕小部件中的图像,如下所示:

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

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

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

    super.onDestroy();
}

但是并不总是调用修改小部件的代码(不显示'System.out.println')。我已经读过onDestroy并不总是被调用。 但我没有找到另一种解决方案?

感谢。

1 个答案:

答案 0 :(得分:5)

is when I kill the application。此处的关键字为kill。通过杀死你的意思是强制关闭应用程序,据我所知。如果是这样,那么你无法改变一些东西。因为当您强行关闭应用程序或者操作系统因某些原因(内存限制,电池优化等)而终止您的应用程序时 - 无法执行某些操作,因为整个应用程序进程(包含您的程序包名称)被简单地杀死通过像Process.killProcess (int pid)之类的东西没有任何回调。在这样的时刻,onDestroy()行为是完全未定义的。它写在文档中:

[..] 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.

所以不要忘记onDestroy()它是一个与{{{1}紧密绑定的方法1}}生命周期而不是整个应用程序生命周期。作为一种解决方法,您应该创建一些Activity's并在其Base Activity中执行您想要的操作,然后使您的应用程序中的所有其他活动继承。

其他(错误的解决方案,不应该在生产代码中使用)是创建一个后台OnPause(),它将循环检查您的应用是否与Service一起运行,如果没有则修改小部件。