使用CountDownTimer类轻松实现倒计时功能
CountDownTimer由系统提供
查资料的时候发现了CountDownTimer这个类之后果断抛弃了以前的倒计时做法
功能:
30秒倒计时每次间隔1秒
参数:
mc.start();方法开始
mc.cancel();方法结束
newMyCountDownTimer(30000,1000);第一个参数表示总的时间为30000毫秒,间隔1000毫秒
直接上代码:
packagecom.example.daojishi; importandroid.app.Activity; importandroid.os.Bundle; importandroid.os.CountDownTimer; importandroid.util.Log; importandroid.view.View; importandroid.widget.TextView; importandroid.widget.Toast; /** * *@authorbaozi * *倒计时的类CountDownTimer * */ publicclassMainActivityextendsActivity{ privateMyCountDownTimermc; privateTextViewtv; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView)findViewById(R.id.show); mc=newMyCountDownTimer(30000,1000); mc.start(); } publicvoidoncancel(Viewview){ Toast.makeText(MainActivity.this,"取消",Toast.LENGTH_LONG).show();//toast有显示时间延迟 mc.cancel(); } publicvoidrestart(Viewview){ Toast.makeText(MainActivity.this,"重新开始",Toast.LENGTH_LONG).show();//toast有显示时间延迟 mc.start(); } /** *继承CountDownTimer防范 * *重写父类的方法onTick()、onFinish() */ classMyCountDownTimerextendsCountDownTimer{ /** * *@parammillisInFuture *表示以毫秒为单位倒计时的总数 * *例如millisInFuture=1000表示1秒 * *@paramcountDownInterval *表示间隔多少微秒调用一次onTick方法 * *例如:countDownInterval=1000;表示每1000毫秒调用一次onTick() * */ publicMyCountDownTimer(longmillisInFuture,longcountDownInterval){ super(millisInFuture,countDownInterval); } @Override publicvoidonFinish(){ tv.setText("done"); } @Override publicvoidonTick(longmillisUntilFinished){ Log.i("MainActivity",millisUntilFinished+""); tv.setText("倒计时("+millisUntilFinished/1000+")..."); } } } //┏┓┏┓ //┏┛┻━━━┛┻┓ //┃┃ //┃━┃ //┃┳┛┗┳┃ //┃┃ //┃┻┃ //┃┃ //┗━┓┏━┛ //┃┃神兽保佑 //┃┃代码无BUG! //┃┗━━━┓ //┃┣┓ //┃┏┛ //┗┓┓┏━┳┓┏┛ //┃┫┫┃┫┫ //┗┻┛┗┻┛
布局:
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world"/> <Button android:id="@+id/button1" android:onClick="oncancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/show" android:layout_below="@+id/show" android:layout_marginLeft="50dp" android:layout_marginTop="106dp" android:text="cancel"/> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button1" android:layout_below="@+id/button1" android:layout_marginTop="63dp" android:onClick="restart" android:text="restart"/> </RelativeLayout>
附:
CountDownTimer源码:
/* *Copyright(C)2008TheAndroidOpenSourceProject * *LicensedundertheApacheLicense,Version2.0(the"License"); *youmaynotusethisfileexceptincompliancewiththeLicense. *YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting,software *distributedundertheLicenseisdistributedonan"ASIS"BASIS, *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. *SeetheLicenseforthespecificlanguagegoverningpermissionsand *limitationsundertheLicense. */ packageandroid.os; importandroid.util.Log; /** *Scheduleacountdownuntilatimeinthefuture,with *regularnotificationsonintervalsalongtheway. * *Exampleofshowinga30secondcountdowninatextfield: * * *newCountDownTimer(30000,1000){ * *publicvoidonTick(longmillisUntilFinished){ *mTextField.setText("secondsremaining:"+millisUntilFinished/1000); *} * *publicvoidonFinish(){ *mTextField.setText("done!"); *} *}.start(); * * *Thecallsto{@link#onTick(long)}aresynchronizedtothisobjectsothat *onecallto{@link#onTick(long)}won'teveroccurbeforetheprevious *callbackiscomplete.Thisisonlyrelevantwhentheimplementationof *{@link#onTick(long)}takesanamountoftimetoexecutethatissignificant *comparedtothecountdowninterval. */ publicabstractclassCountDownTimer{ /** *Millissinceepochwhenalarmshouldstop. */ privatefinallongmMillisInFuture; /** *Theintervalinmillisthattheuserreceivescallbacks */ privatefinallongmCountdownInterval; privatelongmStopTimeInFuture; /** *@parammillisInFutureThenumberofmillisinthefuturefromthecall *to{@link#start()}untilthecountdownisdoneand{@link#onFinish()} *iscalled. *@paramcountDownIntervalTheintervalalongthewaytoreceive *{@link#onTick(long)}callbacks. */ publicCountDownTimer(longmillisInFuture,longcountDownInterval){ mMillisInFuture=millisInFuture; mCountdownInterval=countDownInterval; } /** *Cancelthecountdown. */ publicfinalvoidcancel(){ mHandler.removeMessages(MSG); } /** *Startthecountdown. */ publicsynchronizedfinalCountDownTimerstart(){ if(mMillisInFuture<=0){ onFinish(); returnthis; } mStopTimeInFuture=SystemClock.elapsedRealtime()+mMillisInFuture; mHandler.sendMessage(mHandler.obtainMessage(MSG)); returnthis; } /** *Callbackfiredonregularinterval. *@parammillisUntilFinishedTheamountoftimeuntilfinished. */ publicabstractvoidonTick(longmillisUntilFinished); /** *Callbackfiredwhenthetimeisup. */ publicabstractvoidonFinish(); privatestaticfinalintMSG=1; //handlescountingdown privateHandlermHandler=newHandler(){ @Override publicvoidhandleMessage(Messagemsg){ synchronized(CountDownTimer.this){ finallongmillisLeft=mStopTimeInFuture-SystemClock.elapsedRealtime(); if(millisLeft<=0){ onFinish(); }elseif(millisLeft<mCountdownInterval){ //notick,justdelayuntildone sendMessageDelayed(obtainMessage(MSG),millisLeft); }else{ longlastTickStart=SystemClock.elapsedRealtime(); onTick(millisLeft); //takeintoaccountuser'sonTicktakingtimetoexecute longdelay=lastTickStart+mCountdownInterval-SystemClock.elapsedRealtime(); //specialcase:user'sonTicktookmorethanintervalto //complete,skiptonextinterval while(delay<0)delay+=mCountdownInterval; sendMessageDelayed(obtainMessage(MSG),delay); } } } }; }