Android CountDownTimer案例總結(jié)
一、概述
項(xiàng)目中經(jīng)常用到倒計(jì)時的功能,比如說限時搶購,手機(jī)獲取驗(yàn)證碼等等。而google官方也幫我們封裝好了一個類:CountDownTimer,使我們的開發(fā)更加方便;
二、API
CountDownTimer是一個抽象類,有兩個抽象方法,它的API很簡單
public abstract void onTick(long millisUntilFinished);//這個是每次間隔指定時間的回調(diào),millisUntilFinished:剩余的時間,單位毫秒 public abstract void onFinish();//這個是倒計(jì)時結(jié)束的回調(diào)
使用的時候只需要
new CountDownTimer(long millisInFuture, long countDownInterval)
//millisInFuture:倒計(jì)時的總時長
//countDownInterval:每次的間隔時間 單位都是毫秒
三、基本使用方法
我們以短信驗(yàn)證碼的倒計(jì)時來看,點(diǎn)擊獲取驗(yàn)證碼,倒計(jì)時60s不可點(diǎn)擊
new CountDownTimer(60 * 1000, 1000) { @Override public void onFinish() { if (tvCode != null) { tvCode.setText("重新獲取"); tvCodeWr.setTextColor(Color.parseColor("#E94715")); tvCode.setClickable(true); tvCode.setEnabled(true); } cancel(); } @Override public void onTick(long millisUntilFinished) { if (tvCode != null) { tvCode.setClickable(false); tvCode.setEnabled(false); tvCode.setText(millisUntilFinished / 1000 + "s"); tvCode.setTextColor(Color.parseColor("#999999")); } } }.start();
點(diǎn)擊按鈕,獲取驗(yàn)證碼成功之后就可以執(zhí)行以上操作,最后一定要start,不然不會執(zhí)行
四、使用注意
CountDownTimer使用很簡單,但是坑很多,需要注意避免踩坑。
1、空指針:如果在activity或者fragment關(guān)閉銷毀的時候沒有調(diào)用cancle方法,它的onTick方法還是會繼續(xù)執(zhí)行,這個時候UI控件都為空,不注意判斷的話很容易空指針
2、時間不是太準(zhǔn)的問題:
我們看CountDownTimer的源碼可以看到,在執(zhí)行onTick的方法時,google源碼里面減去了程序執(zhí)行到這里的時候所消耗的時間,這里可以看出google代碼的嚴(yán)謹(jǐn)
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime(); if (millisLeft <= 0) { onFinish(); } else if (millisLeft < mCountdownInterval) { // no tick, just delay until done sendMessageDelayed(obtainMessage(MSG), millisLeft); }
所以一開始倒計(jì)時的時間是59,這里可以在構(gòu)造方法里面稍微加一點(diǎn)時間就可以解決如:
new CountDownTimer(60 * 1000+300, 1000)
3、內(nèi)存泄漏問題
首先我們來看源碼,核心代碼如下
private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { synchronized (CountDownTimer.this) { if (mCancelled) { return; } final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime(); if (millisLeft <= 0) { onFinish(); } else if (millisLeft < mCountdownInterval) { // no tick, just delay until done sendMessageDelayed(obtainMessage(MSG), millisLeft); } else { long lastTickStart = SystemClock.elapsedRealtime(); onTick(millisLeft); // take into account user's onTick taking time to execute long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime(); // special case: user's onTick took more than interval to // complete, skip to next interval while (delay < 0) delay += mCountdownInterval; sendMessageDelayed(obtainMessage(MSG), delay); } } } };
可以看到CountDownTimer的原理還是用到了Handler,所以很容易造成內(nèi)存泄漏問題,當(dāng)Activity或者Fragment關(guān)閉而倒計(jì)時還未結(jié)束的時候,會在后臺一直執(zhí)行,而很多時候我們用倒計(jì)時會有更新UI的操作,而控件都持有activity的引用,長期得不到釋放的話就會造成內(nèi)存泄漏,甚至?xí)斐?所說的空指針問題,所以一般要在activity或fragment銷毀的時候調(diào)用cancle方法。
我自己把這個進(jìn)行了封裝,寫成了一個工具類以供參考:
public class TimeUtils { private String color;//這里可以修改文字顏色 WeakReference<TextView> tvCodeWr;//控件軟引用,防止內(nèi)存泄漏 private CountDownTimer timer; public TimeUtils(TextView tvCode, String color) { super(); this.tvCodeWr = new WeakReference(tvCode); this.color = color; } //這是倒計(jì)時執(zhí)行方法 public void RunTimer() { timer = new CountDownTimer(60 * 1000 - 1, 1000) { @Override public void onFinish() { if (tvCodeWr.get() != null) { tvCodeWr.get().setText("重新獲取"); tvCodeWr.get().setTextColor(Color.parseColor(color)); tvCodeWr.get().setClickable(true); tvCodeWr.get().setEnabled(true); } cancel(); } @Override public void onTick(long millisUntilFinished) { if (tvCodeWr.get() != null) { tvCodeWr.get().setClickable(false); tvCodeWr.get().setEnabled(false); tvCodeWr.get().setText(millisUntilFinished / 1000 + "s"); tvCodeWr.get().setTextColor(Color.parseColor("#999999")); } } }.start(); } //這個方法可以在activity或者fragment銷毀的時候調(diào)用,防止內(nèi)存泄漏 public void cancle() { if (timer != null) { timer.cancel(); timer = null; } } }
到此這篇關(guān)于Android CountDownTimer案例總結(jié)的文章就介紹到這了,更多相關(guān)Android CountDownTimer內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
ExpandableListView實(shí)現(xiàn)手風(fēng)琴效果
這篇文章主要為大家詳細(xì)介紹了ExpandableListView實(shí)現(xiàn)手風(fēng)琴效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08分析CmProcess跨進(jìn)程通信的實(shí)現(xiàn)
CmProcess是Android一個跨進(jìn)程通信框架,無需進(jìn)行bindService()操作,不用定義Service,也不需要定義aidl。 支持IPC級的 Callback,并且支持跨進(jìn)程的事件總線,可同步獲取服務(wù),采用面向接口方式進(jìn)行服務(wù)注冊與調(diào)用,服務(wù)調(diào)用方和使用者完全解耦2021-06-06Android筆記之:onConfigurationChanged詳解
本篇是對Android中onConfigurationChanged的使用進(jìn)行了詳細(xì)的分析介紹。需要的朋友參考下2013-05-05Android實(shí)現(xiàn)收到新短信后自動發(fā)郵件功能
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)收到新短信后自動發(fā)郵件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05Android組件創(chuàng)建DrawerLayout導(dǎo)航
這篇文章主要為大家詳細(xì)介紹了Android組件創(chuàng)建DrawerLayout導(dǎo)航的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01Android提高之SurfaceView的基本用法實(shí)例分析
這篇文章主要介紹了Android提高之SurfaceView的基本用法,非常實(shí)用的功能,需要的朋友可以參考下2014-08-08Android?Flutter中Offstage組件的使用教程詳解
這篇文章主要為大家詳細(xì)介紹了Android?Flutter中Offstage組件的使用教程,文中的示例代碼講解詳細(xì),對我們了解Flutter有一定的幫助,需要的可以參考一下2023-02-02Android ViewPager的MVP架構(gòu)搭建過程
本文主要介紹了ViewPager在Android中的作用以及使用場景,如引導(dǎo)頁、圖片瀏覽器、新聞或文章內(nèi)容的多標(biāo)簽頁等,同時,還詳細(xì)闡述了如何通過MVP架構(gòu)來搭建ViewPager,將視圖和邏輯進(jìn)行解耦,提高代碼的可測試性、可復(fù)用性,使代碼結(jié)構(gòu)更清晰且易于擴(kuò)展功能2024-10-10Android編程之短信竊聽器實(shí)現(xiàn)方法
這篇文章主要介紹了Android編程之短信竊聽器實(shí)現(xiàn)方法,以實(shí)例形式較為詳細(xì)的分析了Android編程實(shí)現(xiàn)竊聽器的具體步驟與實(shí)現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11