在一个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,你可以使用Anko corountines:

更新

doAsync {
   ...
}

弃用

async(UI) {
    // Code run on UI thread
    // Use ref() instead of this@MyActivity
}

最简单的方法,特别是如果你没有context,如果你在使用RxAndroid,你可以这样做:

AndroidSchedulers.mainThread().scheduleDirect {
    runCodeHere()
}

所以最方便的方法是:

import android.os.AsyncTask
import android.os.Handler
import android.os.Looper

object Dispatch {
    fun asyncOnBackground(call: ()->Unit) {
        AsyncTask.execute {
            call()
        }
    }

    fun asyncOnMain(call: ()->Unit) {
        Handler(Looper.getMainLooper()).post {
            call()
        }
    }
}

后:

Dispatch.asyncOnBackground {
    val value = ...// super processing
    Dispatch.asyncOnMain { completion(value)}
}

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

runOnUiThread {
   // Do work..
}

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

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