Mainactivity is as follows:
Package CC. CV; import android. OS. bundle; import android. OS. countdowntimer; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. app. activity;/*** demo example: * countdowntimer complete and detailed example * the code is very simple, directly read the comments. ** countdowntimer is the countdown introduced by android4.0 */public class mainactivity extends activity {private button mstartbutton; private button mcancelbutton; private parameter; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); Init ();} private void Init () {mcountdowntimersubclass = new countdowntimersubclass (15*1000,100 0); mstartbutton = (button) findviewbyid (R. id. startbutton); // starts countdown to mstartbutton. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view) {mcountdowntimersubclass. start () ;}}); // cancels the countdown. // when countdowntimer's start is called again, the countdown starts again. mcancelbutton = (button) findviewbyid (R. id. cancelbutton); mcancelbutton. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view) {mcountdowntimersubclass. cancel () ;}});} private class countdowntimersubclass extends countdowntimer {/*** millisinfuture countdown time * interval between countdowninterval counts every two times */Public limit (long millisinfuture, long countdowninterval) {super (millisinfuture, countdowninterval);}/*** countdown ends */@ overridepublic void onfinish () {system. out. println ("end");}/*** this method is triggered at every countdown time point * millisuntilfinished indicates the remaining time of the entire countdown */@ overridepublic void ontick (long millisuntilfinished) {long remainedseconds = millisuntilfinished/1000; system. out. println ("remaining:" + remainedseconds + "S ");}}}
Main. XML is as follows:
<RelativeLayout xmlns: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" > <Button android:id="@+id/startButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="100dp" android:text="start" /> <Button android:id="@+id/cancelButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@id/startButton" android:layout_marginTop="100dp" android:text="cancel" /></RelativeLayout>
Countdowntimer complete detailed example