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

查看:80
本文介绍了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.

我该如何处理?

推荐答案

如文档中所述 此处,不能保证 onDestroy() 会被调用.相反,使用 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() 中,再次将布尔值设置为 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天全站免登陆