通过实际项目的练习,掌握了几种android基本定时器和延时的用法,这里我想总结一下作为自己的收获,下面列出的是比较简洁的模式,方便简单地在程序中直接调用。
1.CountDownTimer
public class ZpTimerActivity extends Activity {
private CountDownTimer mTimer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
initView();
}
private void initView() {
if (mTimer == null) {
mTimer = new CountDownTimer((long) (5 * 1000), 1000) {
@Override
public void onTick(long millisUntilFinished) {
if (!ZpTimerActivity.this.isFinishing()) {
int remainTime = (int) (millisUntilFinished / 1000L);
Log.e("zpan","======remainTime=====" + remainTime);
}
}
@Override
public void onFinish() {
Log.e("zpan","======onFinish=====");
}
};
mTimer.start();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
}
}
Log:
12-06 16:31:17.809 20276-20276/com.example.zpdemo E/zpan: ======remainTime=====4
12-06 16:31:18.811 20276-20276/com.example.zpdemo E/zpan: ======remainTime=====3
12-06 16:31:19.812 20276-20276/com.example.zpdemo E/zpan: ======remainTime=====2
12-06 16:31:20.813 20276-20276/com.example.zpdemo E/zpan: ======remainTime=====1
12-06 16:31:22.769 20276-20276/com.example.zpdemo E/zpan: ======onFinish=====
三种常用的定时器
1.Handler类的postDelayed方法:
Handler mHandler = new Handler();
Runnable r = new Runnable() {
@Override
public void run() {
//do something
//每隔1s循环执行run方法
mHandler.postDelayed(this, 1000);
}
};
主线程中调用: mHandler.postDelayed(r, 100);//延时100毫秒
2.用handler+timer+timeTask方法:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1){
//do something
}
super.handleMessage(msg);
}
};
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
主线程中调用:timer.schedule(timerTask,1000,500);//延时1s,每隔500毫秒执行一次run方法
3.Thread+handler方法:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1){
//do something
}
super.handleMessage(msg);
}
};
class MyThread extends Thread {//这里也可用Runnable接口实现
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);//每隔1s执行一次
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
主线程中调用:new Thread(new MyThread()).start();
二、三种延时的快捷方法:
1.Handler的postDelayed方法:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//do something
}
}, 1000); //延时1s执行
2.timer + TimerTask方法:
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
//do something
}
},1000);//延时1s执行
3.Thread方法:
new Thread(new MyThread()).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);//延时1s
//do something
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
网友评论