Android中都是任务的实现方式
最近需要完成一个功能:定期的删除聊天记录,涉及到定时任务,经过一段时间的研究,发现大致有两种实现方式:Handler+Timer+TimerTask,AlarmManager.
Handler+Timer+TimerTask
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
handler.sendMsg();
}
};
timer.schedule(task, 1000, 1000);
或者在run()里面实现互相调用
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
AlarmManager
AlarmManager,是Android中的一种系统级别的提示服务,相当于一个闹钟,当闹钟的时间到来的时候,系统就会给我们广播一个PendingIntent,可以理解为Intent的一个包装类,在PendingIntent上加上指定的动作,如setClass,setAction,setFlags....,然后startActivity,sendBroadCast,startServic...来执行相应的操作!
定时任务
public void setRepeating (int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)
public void setInexactRepeating (int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)
说明:同样是用于设置重复闹钟,但是setInexactRepeating 是不准确的,它更加节能,因为系统会将差不多的闹钟进行合并,以避免在不必要地唤醒设备。
几个参数:
type:
ELAPSED_REALTIME:
是相对时间,通过SystemClock.elapsedRealtime()获得当前时间,当设备休眠时,闹钟到来时设备不会唤醒。
ELAPSED_REALTIME_WAKEUP:
是相对时间,由SystemClock.elapsedRealtime(),能唤醒设备。
RTC:
是绝对时间,通过System.currentTimeMillis()获得当前时间,当设备休眠时,闹钟到来时设备不会唤醒。
RTC_WAKEUP :
是绝对时间,通过System.currentTimeMillis()获得当前时间,能唤醒设备。
两种机制的比较
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler。
一句话总结就是AlarmManager提供的是系统级别的服务,效率更高,靠谱。
——————————————————
ps:查api的时候看到CountDownTimer,用来间隔计数,在发送短信验证码功能可以用到。
new CountDownTimer(10000,1000) {
@Override
public void onTick(long arg0) {
mTextView.setText(arg0/1000+"");
}
@Override
public void onFinish() {
mTextView.setText("done");
}
}.start();