谁能告诉我,
如何从消息队列中获取数据(消息)?
或者如何从主线程向其他线程发送消息?
谢谢
最佳答案
如果要在线程上接收消息,则应运行Looper并创建绑定到此循环程序的消息Handler。 UI线程默认情况下具有循环程序。有一个方便的类,用于使用循环程序创建线程,称为HandlerThread。这是一篇关于处理程序和循环程序的好文章:Android Guts: Intro to Loopers and Handlers。
编辑:
HandlerThread thread = new HandlerThread("Thread name");
thread.start();
Looper looper = thread.getLooper();
Handler handler = new Handler(looper) {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case SOME_MESSAGE_ID:
// SOME_MESSAGE_ID is any int value
// do something
break;
// other cases
}
}
};
handler.post(new Runnable() {
@Override
public void run() {
// this code will be executed on the created thread
}
});
// Handler.handleMessage() will be executed on the created thread
// after the previous Runnable is finished
handler.sendEmptyMessage(SOME_MESSAGE_ID);