? ? ? ? ?在Android中經(jīng)常需要定時(shí)循環(huán)執(zhí)行某一段代碼秸抚,大家首先想到的是Timer,在一般的場(chǎng)合下,Timer和TimerTask可以完全勝任雹有,但是在有些情況下,Timer就不能很好的完成定時(shí)循環(huán)任務(wù)臼寄,如與服務(wù)器保持長(zhǎng)連接霸奕,使用輪詢方式。當(dāng)應(yīng)用程序關(guān)閉掉后Timer也將會(huì)被kill掉吉拳。不過(guò)质帅,我們有更好的方式去實(shí)現(xiàn),如使用AlarmClock定時(shí)留攒。
下面對(duì)常用的4中定時(shí)方式進(jìn)行比較煤惩。
1.使用Timer和TimerTask完成。
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// do some task
Log.i("TAG","這是普通方式的TimerTask");
}
},0,3000);
這是常規(guī)的實(shí)現(xiàn)方式炼邀,對(duì)于大多數(shù)人的選擇都會(huì)采用這種方式實(shí)現(xiàn)定時(shí)任務(wù)魄揉。這種實(shí)現(xiàn)方式的生命周期和Acticity的生命周期一樣,當(dāng)Activity銷毀后拭宁,該定時(shí)任務(wù)也會(huì)結(jié)束洛退。即退出該應(yīng)用時(shí),定時(shí)任務(wù)結(jié)束杰标。
2.在Service中開(kāi)啟線程來(lái)實(shí)現(xiàn)定時(shí)器兵怯。
private void serviceTimerTask(){
? ? ? mythread = ?new Thread(new Runnable() {
? ? ?@Override
? ? ? ? ? ? public void run() {
? ? ? ? ? ? ? ? ? ?while (true){
? ? ? ? ? ? ? ? ? ? ?try {
? ? ? ? ? ? ? ? ? ? ? ? Thread.sleep(3000);
? ? ? ? ? ? ? ? ? ? ? ?// do other task
? ? ? ? ? ? ? ? ? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?e.printStackTrace();
? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?});
? ? ? ? ? ? ? ?mythread.start();
? ? }
該方法在onCreate()方法中調(diào)用,在Service中中斷該線程腔剂。該定時(shí)器的生命周期和Service的生命周期一樣媒区,當(dāng)Service銷毀時(shí),該定時(shí)任務(wù)結(jié)束掸犬。當(dāng)退出該應(yīng)用時(shí)驻仅,Service不會(huì)立即銷毀,定時(shí)任務(wù)不會(huì)立即結(jié)束登渣。
3.使用ScheduledExecutorService去實(shí)現(xiàn)噪服。
ScheduledExecutorService scheduleService =Executors.newSingleThreadScheduledExecutor();
? Runable runable = new Runbale(){
? ? ? ?@Override
? ? ? ? ?public void run() {
? ? ? ? // to do task?
? ? ? ? ? ? }
};
ScheduledFuture scheduleGetScanLists ?= ?cheduleService.scheduleAtFixedRate(runable,
0,5,TimeUnit.SECONDS);
取消定時(shí)的時(shí)候操作如下:
if (scheduleGetScanList != null) {
? ? ? ? ?scheduleGetScanList.cancel(true);
? ? ? ? scheduleService.shutdown();
}
4.使用系統(tǒng)的AlarmManager來(lái)實(shí)現(xiàn)定時(shí)任務(wù)。
設(shè)置定時(shí)任務(wù)
private void sendRepeatBroadcast(Context context){
? ? ? ? ? ? ? ? Intent intent = new Intent();
? ? ? ? ? ? ? ?intent.setAction("com.whhx.ydscience");
? ? ? ? ? ? ? ?PendingIntent pendingIntent = ?PendingIntent.getBroadcast(context,0,intent,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?PendingIntent.FLAG_CANCEL_CURRENT);
? ? ? ? ? ? ? AlarmManager alarmManager = (AlarmManager) ? context.
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?getSystemService(ALARM_SERVICE); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
? ? ? ? ? ? ?System.currentTimeMillis(),3000,pendingIntent);
? ? ? ? ? ? ?updateReceiver = new UpdateReceiver();
? ? ? ? ? ? ? IntentFilter intentFilter = new IntentFilter();
? ? ? ? ? ? ?intentFilter.addAction("com.whhx.ydscience");
? ? ? ? ? ? ?registerReceiver(updateReceiver,intentFilter);
}
在廣播接收類中完成定時(shí)任務(wù)胜茧。
public static class UpdateReceiver extends BroadcastReceiver {
@Override
? ? ? ? ? ? ?public void onReceive(Context context, Intent intent) {
? ? ? ? ? ? ? ? ? ? ? ?Log.d("TAG","這是調(diào)用系統(tǒng)時(shí)鐘實(shí)現(xiàn)的TimerTask");
? ? ? ? ? }
}
通過(guò)該方式實(shí)現(xiàn)的定時(shí)器任務(wù)粘优,當(dāng)應(yīng)用退出后仇味,該定時(shí)器任務(wù)也不會(huì)結(jié)束,唯一的結(jié)束方法就是通過(guò)代碼去結(jié)束雹顺。
private void cancleUpdateBroadcast(Context context){
? ? ? ? ? ? AlarmManager alarmManager = (AlarmManager) context.
? ? ? ? ? ? ? ? ? ? ? ? ? getSystemService(ALARM_SERVICE);
? ? ? ? ? ?Intent intent = new Intent(context,UpdateReceiver.class);
? ? ? ? ? ?PendingIntent pendingIntent ?= ?PendingIntent.getBroadcast(context,0,intent,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?PendingIntent.FLAG_CANCEL_CURRENT);
? ? ? ? ? ?alarmManager.cancel(pendingIntent);
}
在使用AlarmManager來(lái)設(shè)置定時(shí)器時(shí)丹墨,在調(diào)用方法setRepeating()方法時(shí)會(huì)傳入四個(gè)參數(shù),這些參數(shù)的含義如下:
type:這個(gè)參數(shù)可以設(shè)置4種類型
ELAPSED_REALTIME:當(dāng)系統(tǒng)進(jìn)入休眠狀態(tài)時(shí)嬉愧,這種類型的時(shí)鐘不會(huì)喚醒系統(tǒng)贩挣。直到系統(tǒng)下次被喚醒才會(huì)傳遞它,該鬧鐘所使用的是絕對(duì)時(shí)間没酣,從系統(tǒng)啟動(dòng)開(kāi)始計(jì)時(shí)的王财,可以通過(guò)調(diào)用SystemClock.elapsedRealtime()獲得。系統(tǒng)值是3裕便。
ELAPSED_REALTIME_WAKEUP:當(dāng)系統(tǒng)進(jìn)入休眠狀態(tài)绒净,這種類型的鬧鐘可以喚醒。系統(tǒng)值是2偿衰。
RTC:當(dāng)系統(tǒng)進(jìn)入休眠狀態(tài)時(shí)挂疆,這種類型的時(shí)鐘不會(huì)喚醒系統(tǒng)。直到系統(tǒng)下次被喚醒才會(huì)傳遞它下翎。該鬧鐘所使用的是相對(duì)時(shí)間缤言。可以調(diào)用System.currentTimeMillis()獲得视事。系統(tǒng)值是 1墨闲。
RTC_WAKEUP:當(dāng)系統(tǒng)進(jìn)入休眠狀態(tài)時(shí),這種類型的時(shí)鐘會(huì)喚醒系統(tǒng)郑口。系統(tǒng)值是0鸳碧。設(shè)為該模式下除了基本的定時(shí)器功能外,還會(huì)發(fā)出警報(bào)聲,例如響鈴犬性、震動(dòng)瞻离。
trrggerAtTime ?第一次運(yùn)行等待的時(shí)間,也就是執(zhí)行延遲時(shí)間乒裆,單位是毫秒套利。
interval ?表示執(zhí)行的間隔時(shí)間,單位是毫秒鹤耍。在設(shè)置間隔時(shí)間時(shí)肉迫,系統(tǒng)默認(rèn)為至少60秒,設(shè)置少于60秒時(shí)稿黄,按照60秒為間隔時(shí)間喊衫,當(dāng)大于60秒時(shí),按照設(shè)置的時(shí)間為間隔時(shí)間杆怕。
operation一個(gè)PendingIntent對(duì)象族购,表示到時(shí)間后要執(zhí)行的操作壳贪。PendingIntent與Intent類似,可以封裝Activity寝杖、BroadcastReceiver和Service违施。但與Intent不同的是,PendingIntent可以脫離應(yīng)用程序而存在瑟幕。
對(duì)比了以上三種定時(shí)器方式磕蒲,選擇合適的定時(shí)器要根據(jù)執(zhí)行任務(wù)的生命周期而定。
(1)當(dāng)定時(shí)任務(wù)同Activity生命周期共存亡只盹,那就使用Timer和TimerTask結(jié)合辣往。
(2) ?當(dāng)定時(shí)器的任務(wù)同Service生命周期供存亡,使用Service中開(kāi)啟線程完成鹿霸。
(3) 完成心跳程序保持長(zhǎng)連接,使用AlarmManager去完成定時(shí)任務(wù)秆乳。
補(bǔ)充:也可以使用Handler去完成定時(shí)任務(wù)懦鼠,代碼如下:
模式1:一直循環(huán)執(zhí)行。
private void handlerExecuteTimerTask(){
? ? ? ? ? ? ? ? ? ? mycircleHandler = new Handler();
? ? ? ? ? ? ? ? ? ? runnable = ?new Runnable() {
? ? ? ? ? ? ? ? ? ? ?@Override
? ? ? ? ? ? ? ? ? ?public void run() {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Log.d("TAG","這是Handler中一直執(zhí)行的TimerTask");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?mycircleHandler.postDelayed(this,3000);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? };
? ? ? ? ? ? ? ? mycircleHandler.postDelayed(runnable,50);
}
當(dāng)結(jié)束循環(huán)時(shí)調(diào)用
mycircleHandler.removeCallbacks(runnable)屹堰;
模式二:僅執(zhí)行一次肛冶。
private void onlyExecuteTimerTask(){
? ? ? ? ? ? ? ? onlyHandler = new Handler();
? ? ? ? ? ? ? ? ?onlyHandler.postDelayed(new Runnable() {
? ? ? ? ? ? ? ? ?@Override
? ? ? ? ? ? ? ? ?public void run() {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Log.d("TAG","這是Handler中執(zhí)行一次的TimerTask");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?onlyHandler.removeCallbacks(this);
? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? },50);
? }