我的函数必须定期在应用程序的主线程上运行,为此我使用了 Handler。代码如下所示:
keepDetecting = true;
final Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
try{
Utils.log("Detection service is running!");
myFunctionThatMustRunOnMainThread();
}
catch (Exception e) {
Utils.log(e.getClass().getSimpleName() + ": " + e.getMessage());
}
finally{
if(keepDetecting) {
handler.postDelayed(this, DETECTION_INTERVAL);
}
}
}
};
handler.post(runnable);
只要应用程序可见,它就可以正常工作。但是,按下主页按钮后,我收到异常消息:Handler sent message to a dead thread。
但是,我知道home键不会停止应用程序,也不会杀死主线程,那么这里发生了什么?
我愿意以其他方式定期在主线程上运行我的函数,如果用户也按下主页按钮,它也需要工作。
编辑: 进一步检查后,我发现尽管处理程序在按下主页按钮后抛出此异常一次,但我的函数仍会定期执行,就好像什么也没发生一样。所以我最终忽略了这条消息。