简体   繁体   English

Acitivity onDestroy并非总是被称为

[英]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). 但是修改窗口小部件的代码并不总是被调用(“ System.out.println”不会出现)。 I have already read that onDestroy is not always called. 我已经读过onDestroy并不总是被调用。 But I don't find another solution ? 但是我找不到其他解决方案吗?

Thanks. 谢谢。

is when I kill the application . is when I kill the application The keyword here is kill . 这里的关键字是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. 因为当您强制关闭应用程序时,或者即使操作系统由于某种原因(内存限制,电池优化等)杀死了您的应用程序,也无法执行任何操作,因为整个应用程序进程(带有您的软件包名称)被简单地杀死了通过类似Process.killProcess (int pid)而没有任何回调。 And onDestroy() behavior in such moments is completely undefined. 并且onDestroy()在这种情况下的行为是完全不确定的。 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. 因此,请不要忘记onDestroy()是与Activity's生命周期紧密相关的方法,而不是与整个应用程序生命周期紧密相关的方法。 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. 解决方法是,创建一些Base Activity并在其OnPause()执行所需的操作,然后使应用程序中的所有其他活动都从该活动继承。

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(); 其他(坏的解决方案,不应在生产代码中使用)是创建一个后台Service ,该Service将循环检查您的应用程序是否正在使用actvityManager.getRunningAppProcesses();运行actvityManager.getRunningAppProcesses(); and modify the widget if not. 并修改窗口小部件(如果没有)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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