A simple alertdialog that displays the countdown.
Dialog display and start countdown. When the countdown ends, alertdialog disappears or alertdialog disappears to cancel the timer.
Do not rely on activity to display dialog, and the permission is required:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Alertdialog creation:
Public void createdialog () {If (malertdialog! = NULL) {return;} layoutinflater Inflater = layoutinflater. From (mcontext); view v = Inflater. Inflate (R. layout. dialog_timertask, null); If (V! = NULL) {mtextview = (textview) v. findviewbyid (R. id. dialog_text);} Builder = new alertdialog. builder (mcontext); builder. settitle ("Countdown:"); builder. setview (V); builder. setnegativebutton ("cancel", null); builder. setpositivebutton ("sure", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {}}); malertdialog = builder. create (); malertdialog. getwindow (). settype (Window Manager. layoutparams. type_system_alert); // display malertdialog. listener (New ondismisslistener () {@ overridepublic void ondismiss (dialoginterface DIALOG) {malertdialog = NULL; If (response! = NULL) {mcountdowntimer. Cancel (); mcountdowntimer = NULL ;}}});}
Countdown:
private void CountDown(){ if (mCountDownTimer!=null) {return;} mCountDownTimer = new CountDownTimer(8000,1000) {@Overridepublic void onTick(long millisUntilFinished) {mTextView.setText(millisUntilFinished/1000+"s");}@Overridepublic void onFinish() {if (mAlertDialog!=null) {mAlertDialog.dismiss();}}};mCountDownTimer.start(); }