发布到绑定到当前线程的处理程序
Posting to Handler tied to current thread
我有一个处理程序,mHandler
,绑定到主线程。 mHandler
驻留在 Service
。假设我现在从主线程 post 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
中的代码语句,因为 post 属于 Runnable
的线程也是要处理 Runnable
的线程?还是它的工作方式不同,因为 Handler
内部使用 MessageQueue
,因此可能 Runnable
s posted 到其他地方的 Handler
(在我之前到达Runnable
)?
- 此外,语句是否可能永远不会 运行,因为
post(Runnable r)
是一个异步调用,因此 onDestroy()
将完成并且 Service
将被终止在 Handler
到达 运行 代码之前由系统执行。
提前谢谢你。
由于 Service
并不意味着一个单独的线程,您的可运行对象将发布在主 Looper
队列的末尾,所以是的,可能有messages/runnables 排在你之前。
同样,由于 Service
并不意味着不同的线程,对 onDestroy
的调用并不意味着 Handler
的线程已终止。在此示例中,您将发布到主循环程序,并且该线程一直处于活动状态,直到应用程序进程终止。
我有一个处理程序,mHandler
,绑定到主线程。 mHandler
驻留在 Service
。假设我现在从主线程 post 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
中的代码语句,因为 post 属于Runnable
的线程也是要处理Runnable
的线程?还是它的工作方式不同,因为Handler
内部使用MessageQueue
,因此可能Runnable
s posted 到其他地方的Handler
(在我之前到达Runnable
)? - 此外,语句是否可能永远不会 运行,因为
post(Runnable r)
是一个异步调用,因此onDestroy()
将完成并且Service
将被终止在Handler
到达 运行 代码之前由系统执行。
提前谢谢你。
由于
Service
并不意味着一个单独的线程,您的可运行对象将发布在主Looper
队列的末尾,所以是的,可能有messages/runnables 排在你之前。同样,由于
Service
并不意味着不同的线程,对onDestroy
的调用并不意味着Handler
的线程已终止。在此示例中,您将发布到主循环程序,并且该线程一直处于活动状态,直到应用程序进程终止。