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

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

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


当前回答

如果你在线程中运行代码,例如延迟一些动作,那么你需要从上下文调用runOnUiThread。例如,如果你的代码在MainActivity类中,那么使用这个:

MainActivity.this.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        myAction();
    }
});

如果你的方法可以从main (UI线程)或其他线程调用,你需要像这样检查:

public void myMethod() {
   if( Looper.myLooper() == Looper.getMainLooper() ) {
       myAction();
   }
   else {

}

其他回答

public void mainWork() {
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            //Add Your Code Here
        }
    });
}

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

遵循这个方法。使用这种方法,您可以简单地从后台线程更新UI。runOnUiThread工作在主(UI)线程上。我认为这个代码片段不那么复杂,而且简单,特别是对初学者来说。

AsyncTask.execute(new Runnable() {
            @Override
            public void run() {

            //code you want to run on the background
            someCode();

           //the code you want to run on main thread
 MainActivity.this.runOnUiThread(new Runnable() {

                    public void run() {

/*the code you want to run after the background operation otherwise they will executed earlier and give you an error*/
                        executeAfterOperation();

                   }
                });
            }
        });

对于服务

在oncreate中创建一个处理程序

 handler = new Handler();

然后像这样使用它

 private void runOnUiThread(Runnable runnable) {
        handler.post(runnable);
    }

我知道这是一个老问题,但我遇到了一个在Kotlin和Java中都使用的主线程一行程序。对于服务来说,这可能不是最好的解决方案,但对于调用将改变片段内UI的东西来说,这是非常简单和明显的。

Java (8):

 getActivity().runOnUiThread(()->{
      //your main thread code
 });

科特林:

this.runOnUiThread {
     //your main thread code
}

使用处理器的更精确的Kotlin代码:

Handler(Looper.getMainLooper()).post {  
 // your codes here run on main Thread
 }

还有另一种简单的方法,如果你没有访问Context的权限。

1).从主循环程序创建一个处理程序:

Handler uiHandler = new Handler(Looper.getMainLooper());

2).实现一个可运行的接口:

Runnable runnable = new Runnable() { // your code here }

3).发布你的Runnable到uiHandler:

uiHandler.post(runnable);

这就是全部;-)享受线程的乐趣,但不要忘记同步它们。