Android中定時器實(shí)現(xiàn)的方式對比

? ? ? ? ?在Android中經(jīng)常需要定時循環(huán)執(zhí)行某一段代碼,大家首先想到的是Timer,在一般的場合下,Timer和TimerTask可以完全勝任,但是在有些情況下,Timer就不能很好的完成定時循環(huán)任務(wù),如與服務(wù)器保持長連接,使用輪詢方式。當(dāng)應(yīng)用程序關(guān)閉掉后Timer也將會被kill掉。不過,我們有更好的方式去實(shí)現(xiàn),如使用AlarmClock定時。

下面對常用的4中定時方式進(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)方式,對于大多數(shù)人的選擇都會采用這種方式實(shí)現(xiàn)定時任務(wù)。這種實(shí)現(xiàn)方式的生命周期和Acticity的生命周期一樣,當(dāng)Activity銷毀后,該定時任務(wù)也會結(jié)束。即退出該應(yīng)用時,定時任務(wù)結(jié)束。

2.在Service中開啟線程來實(shí)現(xiàn)定時器。

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中中斷該線程。該定時器的生命周期和Service的生命周期一樣,當(dāng)Service銷毀時,該定時任務(wù)結(jié)束。當(dāng)退出該應(yīng)用時,Service不會立即銷毀,定時任務(wù)不會立即結(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);

取消定時的時候操作如下:

if (scheduleGetScanList != null) {

? ? ? ? ?scheduleGetScanList.cancel(true);

? ? ? ? scheduleService.shutdown();

}

4.使用系統(tǒng)的AlarmManager來實(shí)現(xiàn)定時任務(wù)。

設(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);

}

在廣播接收類中完成定時任務(wù)。

public static class UpdateReceiver extends BroadcastReceiver {

@Override

? ? ? ? ? ? ?public void onReceive(Context context, Intent intent) {

? ? ? ? ? ? ? ? ? ? ? ?Log.d("TAG","這是調(diào)用系統(tǒng)時鐘實(shí)現(xiàn)的TimerTask");

? ? ? ? ? }

}

通過該方式實(shí)現(xiàn)的定時器任務(wù),當(dāng)應(yīng)用退出后,該定時器任務(wù)也不會結(jié)束,唯一的結(jié)束方法就是通過代碼去結(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來設(shè)置定時器時,在調(diào)用方法setRepeating()方法時會傳入四個參數(shù),這些參數(shù)的含義如下:

type:這個參數(shù)可以設(shè)置4種類型

ELAPSED_REALTIME:當(dāng)系統(tǒng)進(jìn)入休眠狀態(tài)時,這種類型的時鐘不會喚醒系統(tǒng)。直到系統(tǒng)下次被喚醒才會傳遞它,該鬧鐘所使用的是絕對時間,從系統(tǒng)啟動開始計(jì)時的,可以通過調(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)時,這種類型的時鐘不會喚醒系統(tǒng)。直到系統(tǒng)下次被喚醒才會傳遞它。該鬧鐘所使用的是相對時間。可以調(diào)用System.currentTimeMillis()獲得。系統(tǒng)值是 1。

RTC_WAKEUP:當(dāng)系統(tǒng)進(jìn)入休眠狀態(tài)時,這種類型的時鐘會喚醒系統(tǒng)。系統(tǒng)值是0。設(shè)為該模式下除了基本的定時器功能外,還會發(fā)出警報聲,例如響鈴、震動。

trrggerAtTime ?第一次運(yùn)行等待的時間,也就是執(zhí)行延遲時間,單位是毫秒。

interval ?表示執(zhí)行的間隔時間,單位是毫秒。在設(shè)置間隔時間時,系統(tǒng)默認(rèn)為至少60秒,設(shè)置少于60秒時,按照60秒為間隔時間,當(dāng)大于60秒時,按照設(shè)置的時間為間隔時間。

operation一個PendingIntent對象,表示到時間后要執(zhí)行的操作。PendingIntent與Intent類似,可以封裝Activity、BroadcastReceiver和Service。但與Intent不同的是,PendingIntent可以脫離應(yīng)用程序而存在。

對比了以上三種定時器方式,選擇合適的定時器要根據(jù)執(zhí)行任務(wù)的生命周期而定。

(1)當(dāng)定時任務(wù)同Activity生命周期共存亡,那就使用Timer和TimerTask結(jié)合。

(2) ?當(dāng)定時器的任務(wù)同Service生命周期供存亡,使用Service中開啟線程完成。

(3) 完成心跳程序保持長連接,使用AlarmManager去完成定時任務(wù)。

補(bǔ)充:也可以使用Handler去完成定時任務(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)時調(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);

? }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容