我有一个线程,我需要定期执行一些检查,从 Web 获取文件,并将消息发送到主 UI 线程。我什至需要在工作线程的每个循环上使用 UI 线程参数(如地图可见区域)。所以我想我需要实现UIthread和workerThread之间的双向通信。另一个问题是我需要保存添加到地图的每个标记的标识符。我想将 map.addMarker 的结果保存在存储在工作线程中的自定义数组中。这意味着从我更新地图的uithread,我应该告诉workerThread更新标记数组..
这是我的实际工作线程的示例:
class MyThread extends Thread {
private Handler handler;
private MainActivity main;
public MyThread (MainActivity mainClass, Handler handlerClass) {
this.main=mainClass;
this.handler = handlerClass;
}
@Override
public void run(){
while(true){
sleep(2000);
//do my stuffs
//....
//prepare a message for the UI thread
Message msg = handler.obtainMessage();
msg.obj= //here i put my object or i can even use a bundle
handler.sendMessage(msg); //with this i send a message to my UI thread
}
}
}
我的实际问题是,当 UI 线程结束处理从工作线程收到的消息时,我应该对工作线程执行操作。
我想了2个解决方案:
1) 在工作线程上等待,直到 UI 线程处理完消息
2)在UI线程上处理消息,然后向工作线程发送消息。
我不知道如何做解决方案1,所以我尝试了解决方案2。我尝试通过这种方式向我的工作线程(RUN sub)添加一个looper:
class MyThread extends Thread {
private Handler handler;
private MainActivity main;
public MyThread (MainActivity mainClass, Handler handlerClass) {
this.main=mainClass;
this.handler = handlerClass;
}
@Override
public void run(){
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// Act on the message received from my UI thread doing my stuff
}
};
Looper.loop();
while(true){
sleep(2000);
//do my stuffs
//....
//prepare a message for the UI thread
Message msg = handler.obtainMessage();
msg.obj= //here i put my object or i can even use a bundle
handler.sendMessage(msg); //with this i send a message to my UI thread
}
}
}
问题是 Looper.loop() 之后没有执行任何代码行。我读到这是正常的。我阅读了很多文章,但我不明白我应该如何允许执行我的 while 循环,同时处理来自我的 UI 线程的消息。我希望问题很清楚。建议我最好的解决方案。