android應用開發中常常會用到定時器,不可避免的需要用到 TimerTask 定時器任務這個類
下面簡單的一個樣本示範了如何使用TimerTask
這個樣本示範了3秒未有觸屏事件發生則鎖屏(只是設定下文本,意思一下)有觸屏事件則解除鎖定
public class ColTimerTaskActivity extends Activity {
/** Called when the activity is first created. */
private final String TAG = "ColTimerTaskActivity";
private final int EVENT_LOCK_WINDOW = 0x100;
private TextView textView;
private Handler mHandler;
private Timer mTimer;
private MyTimerTask mTimerTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textview);
mHandler = new Handler(){
public void handleMessage(Message message){
Log.i(TAG, "message what = " + message.what);
if (message.what == 0x100){
lockWindow();
}
}
};
mTimer = new Timer(true);
resumeWindow();
StartLockWindowTimer();
}
public boolean onTouchEvent(MotionEvent event)
{
// TODO Auto-generated method stub
resumeWindow();
StartLockWindowTimer();
return super.onTouchEvent(event);
}
public void resumeWindow(){
textView.setText("main window");
}
public void lockWindow(){
textView.setText("lock window");
}
public void StartLockWindowTimer(){
if (mTimer != null){
if (mTimerTask != null){
mTimerTask.cancel(); //將原任務從隊列中移除
}
mTimerTask = new MyTimerTask(); // 建立一個任務
mTimer.schedule(mTimerTask, 3000);
}
}
class MyTimerTask extends TimerTask{
@Override
public void run() {
// TODO Auto-generated method stub
Log.i(TAG, "run...");
Message msg = mHandler.obtainMessage(EVENT_LOCK_WINDOW);
msg.sendToTarget();
}
}
}
這裡需要注意兩個問題:
if (mTimerTask != null){
mTimerTask.cancel(); //將原任務從隊列中移除
}
每次放定時任務前,確保之前任務已從定時器隊列中移除
mTimerTask = new MyTimerTask(); // 建立一個任務
每次放任務都要建立一個對象,否則出現一下錯誤:
ERROR/AndroidRuntime(11761): java.lang.IllegalStateException: TimerTask is scheduled already
所以同一個定時器任務只能被放置一次