在一个android服务,我已经创建线程(s)做一些后台任务。

我有一个线程需要在主线程的消息队列上发布某个任务的情况,例如一个可运行的。

有没有办法得到主线程的处理程序和post Message/Runnable到它从我的其他线程?


当前回答

Kotlin 版本

当你在做某项活动时,就用

runOnUiThread {
    //code that runs in main
}

当你有活动上下文,mContext然后使用

mContext.runOnUiThread {
    //code that runs in main
}

当你在一个没有上下文的地方,然后使用

Handler(Looper.getMainLooper()).post {  
    //code that runs in main
}

其他回答

使用Kotlin,在任何函数中都是这样的:

runOnUiThread {
   // Do work..
}
ContextCompat.getMainExecutor(context).execute {
  // do something
}
public void mainWork() {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            //Add Your Code Here
        }
    });
}

这也可以在服务类中毫无问题地工作。

我能想到的一个方法是:

1)让UI绑定到服务。 2)暴露一个方法,就像下面一个由Binder注册你的处理程序:

public void registerHandler(Handler handler) {
    mHandler = handler;
}

3)在UI线程中,绑定到服务后调用上述方法:

mBinder.registerHandler(new Handler());

4)使用服务线程中的处理程序来发布你的任务:

mHandler.post(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);