在一个android服务中,我创建了一些线程来执行一些后台任务.
我遇到一种情况,线程需要在主线程的消息队列上发布特定任务,例如Runnable
.
有没有办法从我的另一个线程获取Handler
个主线程并发布Message
/Runnable
到它?
在一个android服务中,我创建了一些线程来执行一些后台任务.
我遇到一种情况,线程需要在主线程的消息队列上发布特定任务,例如Runnable
.
有没有办法从我的另一个线程获取Handler
个主线程并发布Message
/Runnable
到它?
注意:这个答案已经引起了很多关注,我需要更新它.自从原始答案发布后,@dzeikei的 comments 几乎和原始答案一样受到关注.以下是两种可能的解决方案:
1. If your background thread has a reference to a 100 object:
确保您的后台工作线程可以访问上下文对象(可以是应用程序上下文或服务上下文).然后,只需在后台工作线程中执行以下操作:
// 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. If your background thread does not have (or need) a 100 object
(由@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);