在一个android服务,我已经创建线程(s)做一些后台任务。
我有一个线程需要在主线程的消息队列上发布某个任务的情况,例如一个可运行的。
有没有办法得到主线程的处理程序和post Message/Runnable到它从我的其他线程?
在一个android服务,我已经创建线程(s)做一些后台任务。
我有一个线程需要在主线程的消息队列上发布某个任务的情况,例如一个可运行的。
有没有办法得到主线程的处理程序和post Message/Runnable到它从我的其他线程?
当前回答
使用处理器的更精确的Kotlin代码:
Handler(Looper.getMainLooper()).post {
// your codes here run on main Thread
}
其他回答
注意:这个答案已经得到了如此多的关注,我需要更新它。自从原来的答案被发布后,@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);
我知道这是一个老问题,但我遇到了一个在Kotlin和Java中都使用的主线程一行程序。对于服务来说,这可能不是最好的解决方案,但对于调用将改变片段内UI的东西来说,这是非常简单和明显的。
Java (8):
getActivity().runOnUiThread(()->{
//your main thread code
});
科特林:
this.runOnUiThread {
//your main thread code
}
对于Kotlin,你可以使用Anko corountines:
更新
doAsync {
...
}
弃用
async(UI) {
// Code run on UI thread
// Use ref() instead of this@MyActivity
}
如果你在线程中运行代码,例如延迟一些动作,那么你需要从上下文调用runOnUiThread。例如,如果你的代码在MainActivity类中,那么使用这个:
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
myAction();
}
});
如果你的方法可以从main (UI线程)或其他线程调用,你需要像这样检查:
public void myMethod() {
if( Looper.myLooper() == Looper.getMainLooper() ) {
myAction();
}
else {
}
压缩代码块如下所示:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
// things to do on the main thread
}
});
这并不涉及传递活动引用或应用程序引用。
芬兰湾的科特林相当于:
Handler(Looper.getMainLooper()).post(Runnable {
// things to do on the main thread
})