在一个android服务,我已经创建线程(s)做一些后台任务。
我有一个线程需要在主线程的消息队列上发布某个任务的情况,例如一个可运行的。
有没有办法得到主线程的处理程序和post Message/Runnable到它从我的其他线程?
在一个android服务,我已经创建线程(s)做一些后台任务。
我有一个线程需要在主线程的消息队列上发布某个任务的情况,例如一个可运行的。
有没有办法得到主线程的处理程序和post Message/Runnable到它从我的其他线程?
当前回答
我知道这是一个老问题,但我遇到了一个在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
}
public void mainWork() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//Add Your Code Here
}
});
}
这也可以在服务类中毫无问题地工作。
所以最方便的方法是:
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)}
}
最简单的方法,特别是如果你没有context,如果你在使用RxAndroid,你可以这样做:
AndroidSchedulers.mainThread().scheduleDirect {
runCodeHere()
}
我能想到的一个方法是:
1)让UI绑定到服务。 2)暴露一个方法,就像下面一个由Binder注册你的处理程序:
public void registerHandler(Handler handler) {
mHandler = handler;
}
3)在UI线程中,绑定到服务后调用上述方法:
mBinder.registerHandler(new Handler());
4)使用服务线程中的处理程序来发布你的任务:
mHandler.post(runnable);