停止在輔助線程的方法,我想實現的方式來觸發地圖覆蓋數據的請求(來自外部Web服務器),只有當它似乎有必要。通過直接中斷
要做到這一點我在想有屏幕觸摸事件外螺紋觸發一個計數器,如果用戶將鼠標懸停在地圖區域而不觸及約一秒的請求畫面被髮送。
事件流會是這個樣子:
UI Thread -down press-----release-----down---release---------------------->
v v v
Worker Thread -----------------start------stop----start---------------send---->
timer======timer timer==============request
<1s 1s
我遇到麻煩UIthread停止wait()調用的方法,並拋出一個InterruptionException,因此走出了方法體的前它可以執行請求。 我基本上只想繞過線程的任何消息隊列,並立即停止執行,雖然我不確定這是可能的。我在這裏跟蹤?我的代碼如下所示:
public class ExtendedMapView extends MapView {
private final static int DOWN_PRESS = 1;
private final static int RELEASE_PRESS = 2;
private Handler countThreadHandler;
private TouchThread touchMonitor ;
public ExtendedMapView(Context context, AttributeSet attrs) {
super(context, attrs);
touchMonitor = new TouchThread();
touchMonitor.start();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch(ev.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("TEST", "Touch Screen");
touchMonitor.interrupt();
break;
case MotionEvent.ACTION_UP:
Log.d("TEST", "Touch released");
countThreadHandler.sendMessage(Message.obtain(countThreadHandler,RELEASE_PRESS));
break;
default:
break;
}
return super.onTouchEvent(ev);
}
private class TouchThread extends Thread {
@Override
public void interrupt() {
super.interrupt();
Log.d("TEST", "Thread interrupted");
}
@Override
public synchronized void run() {
try {
Looper.prepare();
countThreadHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case DOWN_PRESS:
runOnDown();
break;
case RELEASE_PRESS:
runOnUp();
break;
}
};
Looper.loop();
Log.d("TEST", "thread started");
} catch (Throwable t) {
t.printStackTrace();
Log.d("TEST", "thread not started");
}
}
private synchronized void runOnUp() {
Log.d("TEST", "count started");
downPressed = false;
try {
Log.d("TEST", "Timer started");
wait(1000);
//SEND REST MSG BASED OFF RECIEVED MAP FILL CO-ORDS
Log.d("TEST", "send Rest msg--------------------->");
} catch (InterruptedException e) {
e.printStackTrace();
Log.d("TEST", "Received Interruption NIIICE");
}
}
}
}
我會一直在閱讀和嘗試的平均時間。謝謝:d
感謝隊友,這似乎是一個非常乾淨的方式來做到這一點,正是我之後。我實際上設法通過調用中斷來實現它。儘管如此,我會盡力去做。再次感謝 – manno23 2011-05-09 10:31:28