很多時候需要重複性的做某些事情,可以用Handler+Runnable的方式很簡單完成。
1.建立Handler與Runnable物件
private Handler updateHandler = new Handler(); //假如跳出執行緒Looper問題,可以改成 private Handler updateHandler = new Handler(Looper.getMainLooper()); private Runnable updateRunnable = null;
2.建立Runnable的程式碼區塊
private void checkLocation(){
updateRunnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//要重複做的事情
if(currentLocation != null) {
Toast.makeText(getApplication(),"目前位置:" + currentLocation.getLongitude() + " , " + currentLocation.getLatitude(), Toast.LENGTH_LONG).show();
}
//5秒後執行
updateHandler.postDelayed(this, 5000);
}
};
}
3.啟動定時器
updateHandler.postDelayed(updateRunnable, 5000);//每5秒執行一次runnable.
4.不用時記得關閉
updateHandler.removeCallbacks(updateRunnable);
-END-
發佈留言