1.倒计时三秒后做任务
private HandlerThread handlerThread;
private Handler mHander;
Runnable delayDo = new Runnable() {
@Override
public void run() {
Log.d("ldx",Thread.currentThread()+""); //Thread[HandlerThread,5,main]
Log.d("ldx", "当前线程是不是主线程"+(Looper.getMainLooper().getThread() == Thread.currentThread()));
Log.d("ldx", "延迟3秒后做这个事情");
// 定时任务,每秒执行delayDo
mHander.postDelayed(delayDo, 1*1000);
}
};
// 子线程做任务
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
Handler hander = new Handler(handlerThread.getLooper());
// 主线程做任务
mHander = new Handler(Looper.getMainLooper());
mHander.postDelayed(delayDo, 3*1000);
// 不用的时候,需要手动销毁线程
@Override
protected void onDestroy() {
super.onDestroy();
handlerThread.quit();
}
2.程序退到后台,需要暂停定时器
// 点击Home键进入后台
@Override
protected void onStop() {
super.onStop();
Log.d("ldx", "onStop 被调用了");
mHander.removeCallbacks(delayDo);
}
// 点击图标再次进入应用,会调用onResume,不会调用onRestart
// 再次进入应用程序时,onRestart,后调用onResume
@Override
protected void onResume() {
super.onResume();
Log.d("ldx", "onResume 被调用了");
mHander.postDelayed(delayDo, 1*1000);
}
// 点击图标再次进入应用,会调用onResume,不会调用onRestart
// 再次进入应用程序时,onRestart,后调用onResume
@Override
protected void onRestart() {
super.onRestart();
Log.d("ldx", "onRestart 被调用了");
}