从另一个线程在主线程中运行代码
在一个 android 服务中,我创建了线程来执行一些后台任务。
我有一个线程需要在主线程的消息队列上发布某些任务的情况,例如Runnable
.
有没有办法从我的另一个线程获取Handler
主线程并发布Message
/到它?Runnable
-
注意:这个答案引起了如此多的关注,我需要更新它。自从发布了原始答案以来,@dzeikei 的评论几乎与原始答案一样受到关注。所以这里有两种可能的解决方案:
1.如果你的后台线程有一个
Context
对象的引用:确保您的后台工作线程可以访问 Context 对象(可以是应用程序上下文或服务上下文)。然后只需在后台工作线程中执行此操作:
// Get a handler that can be used to post to the main thread Handler mainHandler = new Handler(context.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() {....} // This is your code }; mainHandler.post(myRunnable);
2.如果你的后台线程没有(或不需要)一个
Context
对象(由@dzeikei 建议):
// Get a handler that can be used to post to the main thread Handler mainHandler = new Handler(Looper.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() {....} // This is your code }; mainHandler.post(myRunnable);