从另一个线程在主线程中运行代码 [英] Running code in main thread from another thread
问题描述
在一个 android 服务中,我创建了线程来执行一些后台任务.
In an android service I have created thread(s) for doing some background task.
我有一个线程需要在主线程的消息队列上发布某些任务的情况,例如一个 Runnable
.
I have a situation where a thread needs to post certain task on main thread's message queue, for example a Runnable
.
有没有办法获取主线程的 Handler
并将 Message
/Runnable
从我的另一个线程发送给它?
Is there a way to get Handler
of the main thread and post Message
/Runnable
to it from my other thread?
推荐答案
注意:这个答案受到了如此多的关注,我需要更新它.自从发布原始答案以来,@dzeikei 的评论几乎与原始答案一样受到关注.所以这里有两种可能的解决方案:
NOTE: This answer has gotten so much attention, that I need to update it. Since the original answer was posted, the comment from @dzeikei has gotten almost as much attention as the original answer. So here are 2 possible solutions:
1.如果您的后台线程引用了 Context
对象:
1. If your background thread has a reference to a Context
object:
确保您的后台工作线程可以访问上下文对象(可以是应用程序上下文或服务上下文).然后在后台工作线程中执行此操作:
Make sure that your background worker threads have access to a Context object (can be the Application context or the Service context). Then just do this in the background worker thread:
// 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
对象
2. If your background thread does not have (or need) a Context
object
(由@dzeikei 建议):
(suggested by @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);
这篇关于从另一个线程在主线程中运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!