运行$ C $在主线程从另一个线程C- [英] Running code in main thread from another thread
本文介绍了运行$ C $在主线程从另一个线程C-的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一个机器人服务,我已经创建的线程(S)做一些后台任务。
In an android service I have created thread(s) for doing some background task.
我有一种情况,该线程需要张贴在主线程的消息阙某项任务,例如可运行。
I have a situation where the thread need to post certain task on main thread's message que, for example a runnable.
有没有办法让主线程和后消息处理程序/可运行它从我的其他线程?
Is there a way to get Handler of the main thread and post message/runnable to it from my other thread ?
谢谢
推荐答案
请确保您的后台工作线程可以访问一个Context对象(可以是应用程序上下文或服务上下文)。然后,只需为此在后台工作线程:
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);
这篇关于运行$ C $在主线程从另一个线程C-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文