【发布时间】:2015-02-19 23:00:46
【问题描述】:
我有一个处理程序,mHandler,绑定到主线程。 mHandler 位于 Service 中。假设我现在从主线程中将Runnable 发布到mHandler,如下所示:
public class SomeService extends Service {
// Handler is created on the main thread
// (and hence it is tied to the main thread)
private Handler mHandler = new Handler();
@Override
public void onDestroy() {
// onDestroy runs on the main thread
// Is the code in this Runnable processed right away?
mHandler.post(new Runnable() {
// (Some code statements that are to be run on the main thread)
...
});
super.onDestroy();
}
}
我知道这个例子有点傻,因为Handler 是不必要的。但是,这是这个问题的一个很好的例子。
现在我的问题是:
-
Runnable中的代码语句是否会被立即处理,因为发布Runnable的线程也是处理Runnable的线程?还是因为Handler在内部使用MessageQueue并因此可能有Runnables 发布到其他地方的Handler(在我的Runnable之前到达),所以它的工作方式不同? - 此外,语句是否可能永远不会运行,因为
post(Runnable r)是一个异步调用,因此onDestroy()将完成并且Service将在Handler开始运行之前被系统杀死代码。
提前谢谢你。
【问题讨论】: