简体   繁体   English

并非总是调用Android Activity onDestroy(),如果调用,则仅执行部分代码

[英]Android Activity onDestroy() is not always called and if called only part of the code is executed

onDestroy() is not always called. onDestroy()并不总是被调用。 If called, only part of the code is executed. 如果被调用,则仅执行部分代码。 And most of the time in LogCat I only see the message "gps state on destroy called first". 而且在LogCat中 ,大多数时候我只会看到消息“ gps销毁状态首先被调用”。 Why is that? 这是为什么?

protected void onDestroy() {
    super.onDestroy();
    Log.d("on destroy called", "gps state on destroy called first");

    editor.putBoolean("gpsOn", false);
    Log.d("on destroy called", "gps state on destroy called second");
    editor.commit();

    Log.d("on destroy called", "gps state on destroy called third");
    stopRouteTracking();
    Log.d("on destroy called", "gps state on destroy called  fourth");
}

Take a look at this: 看看这个:

Activity OnDestroy never called? 活动OnDestroy从未调用过?

And this: 和这个:

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

Basically, there's never a guarantee that onDestroy() will be called, and in some cases processes such as your app will be killed directly, bypassing the method call anyway. 基本上,永远无法保证onDestroy()将被调用,并且在某些情况下,诸如应用程序之类的进程将直接被杀死,无论如何都要绕过方法调用。

In the android developer documentation here , you can see that - 此处的android开发人员文档中,您可以看到-

for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed. 对于那些标记为可杀死的方法,该方法返回后,承载活动的进程可能会在不执行其代码另一行的情况下,随时被系统杀死。 Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. 因此,您应该使用onPause()方法将任何持久性数据(例如用户编辑)写入存储。

and onStop() and onDestroy() both are marked as killable. onStop()和onDestroy()都标记为可杀死。

This may be the reason that only part of the code written in onDestroy() is being called since process can be destroyed at any time after it executes onStop(). 这可能是因为只调用部分用onDestroy()编写的代码的原因,因为进程在执行onStop()之后可以随时销毁。

@Chris's answer is correct, however your issue where only part of your code is called can arise from the call to super.onDestroy() before calling your code. super.onDestroy()的答案是正确的,但是在调用代码之前,对super.onDestroy()的调用可能会导致只调用部分代码的问题。 super.onDestroy() should be called at the end because then your code will be called before it is destroyed. super.onDestroy()应该在末尾被调用,因为这样您的代码将在销毁之前被调用。

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

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