Android应用不会调用"onDestroy()",被杀死时(ICS) [英] Android app doesn't call "onDestroy()" when killed (ICS)

查看:579
本文介绍了Android应用不会调用"onDestroy()",被杀死时(ICS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用蓝牙通信(使用专有协议)开发一个android应用程序,我需要赶上该应用程序被杀的那一刻.

I'm developing an android app using bluetooth communication (using a propetary protocol) and I need to catch the moment when the app is killed.

我想使用"onDestroy()"方法,但是每次杀死应用程序时都不会调用它. 我注意到,当我按下后退"按钮时,只有在从任务管理器中终止该应用程序时,它才会被调用.

I wanted to use the "onDestroy()" method but it isn't called every time the app is killed. I noticed that it is called when I press the back button and, only sometimes, when I kill the app from the task manager.

问题是:如何捕捉应用程序被杀死之前的那一刻?

The question is: How can I catch the moment before the app is killed?

这是我尝试使用的代码:

Here is the code I tried to use:

@Override
public void onDestroy() {
    sendMessage(msg);
    Log.d("SampleApp", "destroy");
    super.onDestroy();
}

@Override
public void finish(){

    sendMessage(msg);
    Log.d("SampleApp", "finish");
    super.finish();
}

不幸的是,每次我从任务管理器关闭应用程序时,都不会调用finish(),也不会调用onDestroy.

Unfortunately finish() is never called and onDestroy isn't called every time I close the app from the task manager.

我该如何处理?

推荐答案

如文档 onPause()来完成您想做的事情每当应用程序移入后台时,仅在您的应用程序被杀死时将要运行的代码保留在onDestroy()中.

As stated in the documentation here, there is no guarantee that onDestroy() will ever be called. Instead, use onPause() to do the things you want to do whenever the app moves into the background, and leave only that code in onDestroy() that you want run when your app is killed.

从您的评论看来,您希望每当应用程序进入后台时都运行一些代码,但是如果您启动了意图,则不想在应用程序进入后台时运行一些代码. AFAIK,默认情况下,Android中没有方法可以处理此问题,但是您可以使用以下方法:

From your comments, it seems that you want to run some code whenever your app goes into the background, but not if it went into the background because you launched an intent. AFAIK, there is no method in Android that handles this by default, but you can use something like this:

具有如下布尔值:

boolean usedIntent = false;

现在使用意图之前,将布尔值设置为true.现在,在您的onPause()中,将意图大小写的代码移动到一个if块中,如下所示:

Now before using an intent, set the boolean to true. Now in your onPause(), move the code for the intent case into an if block like this one:

if(usedIntent)
{
//Your code
}

最后,在您的onResume()中,将boolean值再次设置为false,以便它可以处理您的应用程序无意间被适当地移入后台的情况.

Finally, in your onResume(), set the boolean to false again so that it can deal with your app being moved into the background by a non intent means properly.

这篇关于Android应用不会调用"onDestroy()",被杀死时(ICS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆