Android timing task and the realization of alarm clock

There are many ways to implement timing in android. The common combination of Handler and Thread, handler.postDelayed, and AlarmManger to be used can implement timing tasks, but the usage scenarios are quite different. Here is how to use AlarmManager to implement timing tasks. Knowledge points involved:

1) BroadCastReceiver task receiving

2) CountDownTimer countdown

3) AlertDialog task reminder

4) AlarmManager scheduled tasks

The demand realized here is to shut down at 24 o'clock every day. Some devices are customized systems to prevent the application from being stuck for a long time without shutting down. When shutting down, the system will prompt the user and shut down automatically if there is no operation.

The first step is to implement a simple layout. Write two buttons in the layout, one for setting and one for canceling
Step 2: initialize page layout and Button

public class MainActivity extends AppCompatActivity

implements View.OnClickListener{

Button btn_set,btn_cancel;

AlarmManager am;

PendingIntent pi;

long time;

@Override

protected void onCreate(@NullableBundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

initView();

}

private void initView(){
btn_set=findViewById(R.id.btn_Set);

btn_cancel=findViewById(R.id.btn_Cancel);

btn_set.setOnClickListener(this);

btn_cancel.setOnClickListener(this);

initAlarm();

}

@Override

public void onClick(View v) {

switch(v.getId()){

case R.id.btn_Set:

setAlarm();

break;

case R.id.btn_Cancel:

cancelAlarm();

break;

}

}

// Initialize Alarm

private void initAlarm(){

pi=PendingIntent.getBroadcast(this,0,getMsgIntent(),0);

time=System.currentTimeMillis();

am= (AlarmManager) getSystemService(ALARM_SERVICE);

}

private Intent getMsgIntent(){

//AlarmReceiver is broadcast in the following code

Intent intent=newIntent(this,AlarmReceiver.class);

intent.setAction(AlarmReceiver.BC_ACTION);

intent.putExtra("msg","Alarm on");

return intent;

}

//Set scheduled tasks

private void setAlarm(){

//Changes of android Api different settings in different versions

if(Build.VERSION.SDK_INT<19){

am.set(AlarmManager.RTC_WAKEUP,getTimeDiff(),pi);

}else{

am.setExact(AlarmManager.RTC_WAKEUP,getTimeDiff(),pi);

}

}

public long getTimeDiff(){

//The setting here is 15:55 of the day. Note that the time can be set freely with the accuracy of seconds

Calendar ca=Calendar.getInstance();

ca.set(Calendar.HOUR_OF_DAY,15);

ca.set(Calendar.MINUTE,55);

ca.set(Calendar.SECOND,0);

return ca.getTimeInMillis();

}

//Cancel scheduled task execution

private void cancelAlarm(){

am.cancel(pi);

}

}

Broadcast main code

import android.app.AlertDialog;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.os.Build;

import android.os.CountDownTimer;

import android.util.Log;

import android.view.WindowManager;

import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

private String TAG=this.getClass().getSimpleName();

public static final String BC_ACTION="com.ex.action.BC_ACTION";

private AlertDialog.Builder builder;

CountDownTimer timer;

@Override

public void onReceive(Context context,Intent intent) {

String msg=intent.getStringExtra("msg");

Log.i(TAG,"get Receiver msg :"+msg);

Toast.makeText(context,msg,Toast.LENGTH_LONG).show();

showConfirmDialog(context);

}

private void showConfirmDialog(Context context){

builder=newAlertDialog.Builder(context);

builder.setTitle("Tips")

.setMessage("Will shut down in 30 seconds")

.setCancelable(false)

.setPositiveButton("cancel",

newDialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, intwhich) {

if(timer!=null)timer.cancel();

}

});

setShowDialogType(context,builder.create());

}

private void setShowDialogType(Context context,AlertDialog alertDialog){

int type;

if(Build.VERSION.SDK_INT>24){

type= WindowManager.LayoutParams.TYPE_PHONE;

}else if(Build.VERSION.SDK_INT>18){

type= WindowManager.LayoutParams.TYPE_TOAST;

}else{

type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;

}

alertDialog.getWindow().setType(type);

alertDialog.show();

//Turn on the countdown and set the countdown time (seconds)

startCountDownTimer(context,alertDialog,30);

}

private void startCountDownTimer(final Context context,final AlertDialog alertDialog,inttime){

timer=newCountDownTimer(time*1000,1000) {

@Override

public void onTick(long millisUntilFinished) {

//Countdown prompt text

Log.i(TAG,"onTick time :"+millisUntilFinished);

alertDialog.setMessage("Will be in"+(millisUntilFinished/1000)+"Shutdown");

}

@Override

public void onFinish() {

//End of countdown

Log.i(TAG,"The countdown is over!");

alertDialog.dismiss();

//Countdown to finish a scheduled task

//                shutdown(context);

}

};

timer.start();

}

//shoutDown requires system permission to execute, otherwise permission exception will be prompted

public void shutDown(Context context) {

String action ="android.intent.action.ACTION_REQUEST_SHUTDOWN";

String extraName ="android.intent.extra.USER_REQUESTED_SHUTDOWN";

Intent intent =newIntent(action);

intent.putExtra(extraName, true);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(intent);

}

}

Declare in the Android manifest.xml configuration file:

Realize the timing task according to the facts

The pop-up box requires the following permissions:

< uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

Tags: Android xml

Posted on Sat, 02 May 2020 17:05:05 -0700 by Mikell