Android - 定期偵測程式
由於或許很多時候會有每多久要執行一次的程式
要常常重複撰寫timertask、timer、handler,嫌太麻煩,我做了一個類別,處理這些東西。讓程式少寫一些
public class TimingDetectHelper {
private Timer mTimer;
private Handler mHandler;
private DetectTimerTask mTimerTask;
private long mDuration = 5*60*1000;//間隔啟機時間,預設5分鐘
/**
* 偵測查詢判斷
*/
public void init(Handler handler,long duration) {
mTimer = new Timer();
mHandler = handler;
mDuration = duration;
}
// 啟動自動偵測
public void startPlay() {
try {
long duration = mDuration; //mDuration執行一次
if (mTimer != null) {
if (mTimerTask != null) {
mTimerTask.cancel();
}
mTimerTask = new DetectTimerTask();
mTimer.schedule(mTimerTask, duration, duration);// duration秒後執行,每隔duration秒執行一次
}
}catch (Exception ex) {
ex.printStackTrace();
}
}
// 暂停自動偵測
public void stopPlay() {
try {
if (mTimerTask != null) {
mTimerTask.cancel();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private class DetectTimerTask extends TimerTask {
@Override
public void run() {
Message msg = new Message();
mHandler.sendMessage(msg);
}
}
}