在一个android服务,我已经创建线程(s)做一些后台任务。
我有一个线程需要在主线程的消息队列上发布某个任务的情况,例如一个可运行的。
有没有办法得到主线程的处理程序和post Message/Runnable到它从我的其他线程?
在一个android服务,我已经创建线程(s)做一些后台任务。
我有一个线程需要在主线程的消息队列上发布某个任务的情况,例如一个可运行的。
有没有办法得到主线程的处理程序和post Message/Runnable到它从我的其他线程?
当前回答
正如下面一位评论者正确指出的那样,这不是服务的通用解决方案,只适用于从您的活动中启动的线程(服务可以是这样的线程,但不是所有线程都是)。 关于服务-活动通信这个复杂的话题,请阅读官方文档的整个服务部分——它很复杂,所以了解基本知识是有好处的: http://developer.android.com/guide/components/services.html#Notifications
下面的方法可能适用于最简单的情况:
如果我理解正确的话,你需要在应用程序的GUI线程中执行一些代码(不能考虑任何其他称为“主线程”的线程)。 为此,Activity上有一个方法:
someActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
//Your code to run in GUI thread here
}//public void run() {
});
道格:http://developer.android.com/reference/android/app/Activity.html runOnUiThread % 28 java.lang.runnable % 29
希望这就是你要找的。
其他回答
使用处理器的更精确的Kotlin代码:
Handler(Looper.getMainLooper()).post {
// your codes here run on main Thread
}
压缩代码块如下所示:
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
})
遵循这个方法。使用这种方法,您可以简单地从后台线程更新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);
}
我能想到的一个方法是:
1)让UI绑定到服务。 2)暴露一个方法,就像下面一个由Binder注册你的处理程序:
public void registerHandler(Handler handler) {
mHandler = handler;
}
3)在UI线程中,绑定到服务后调用上述方法:
mBinder.registerHandler(new Handler());
4)使用服务线程中的处理程序来发布你的任务:
mHandler.post(runnable);
所以最方便的方法是:
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)}
}