Android 中的Force Close

今天写程序时遇到一个问题,领导希望在点击了setting里的force close 后,程序依然能够响应以前用alarmManager注册的receiver。

在网上看到了一些文章,写的是如何建立一个无法被force close的service,目前,没能找到好用的方法,可能他们的方法是针对老版本的sdk的,而我使用的是4.0版本的sdk。例如,有一篇文章说的是利用系统的android.intent.action.TIME_TICK来每分钟检查service,但是根据我的测试,程序在force close后,它根本接受不到android.intent.action.TIME_TICK这条broadcast,也就不用再想其他问题了。又比如,有人说通过监听Intent.ACTION_PACKAGE_RESTARTED可以,但实际情况是,这条broadcast也是无法被监听到的!

之后参看了一下stackoverflow,找到了答案,以下是原文

Hello Everybody, I´m having the following issue.

The ApplicationManager is killing the process of my application when the user presses on "FORCE STOP" on the Aplication Manager.

MENU-> SETTINGS -> APPLICATIONS -> MANAGE APPLICATIONS -> My APP .> FORCE STOP.

According to the documentation a broadcast action is sent: Intent.ACTION_PACKAGE_RESTARTED Broadcast Action: The user has restarted a package, and all of its processes have been killed. All runtime state associated with it (processes, alarms, notifications, etc) should be removed. Note that the restarted package does not  receive this broadcast. The data contains the name of the package.

另外的一遍文章说,如果你进行了force close,相应的程序就不能接受到任何broadcast了,比如开机启动的广播。如果想能够接受到开机启动的广播,必须手动启动这个应用程序,那么下一次开机时,程序才能正确响应开机的广播。这个需要验证一下,验证后,把结果发上来。---------经过验证了,是这样的!force close后,重启手机,目标程序对于android.intent.action.BOOT_COMPLETED这样的广播也接收不到了,手动启动程序后,不进行force close,再次重启,程序就又可以接收到这条广播了。(我这里的重启是通过拿下电池的重启,是真正的断电重启,不是用软件关闭手机,再打开手机。貌似用手机中的“重新启动”,也可以达到一样的效果。)

原文地址:https://www.cnblogs.com/breezemist/p/3419956.html