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

时间:2013-08-21 15:34:24

标签: android ondestroy

onDestroy()并不总是被调用。如果被调用,则只执行部分代码 而且大部分时间在LogCat中我只看到消息“首先调用destroy的gps状态”。那是为什么?

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");      





}

3 个答案:

答案 0 :(得分:13)

看看这个:

Activity OnDestroy never called?

而且:

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

基本上,从来没有保证会调用onDestroy(),在某些情况下,您的应用等流程会被直接杀死,无论如何都会绕过方法调用。

答案 1 :(得分:8)

在android开发者文档here中,您可以看到 -

  

对于那些被标记为可填充的方法,在该方法之后   返回托管活动的进程可能被系统杀死   在任何时候都没有执行其代码的另一行。因为   对此,您应该使用onPause()方法来编写任何持久性   数据(例如用户编辑)到存储。

和onStop()以及onDestroy()都被标记为killable。

这可能是因为只有部分代码在onDestroy()中被调用,因为在执行onStop()之后可以随时销毁该进程。

答案 2 :(得分:0)

@Chris的回答是正确的,但是在调用代码之前调用func pinColor(type:String) -> UIColor{ var color = UIColor.purpleColor() switch category { case "Category A": color = UIColor(red: 255/255, green: 36/255, blue: 0, alpha: 1) case "Category B": color = UIColor(red: 0, green: 36/255, blue: 255/255, alpha: 1) default: color = UIColor.whiteColor() } return color 的问题可能只会导致调用部分代码的问题。最后应该调用super.onDestroy()因为那么你的代码会在销毁之前被调用。