Android Realizes Timing Task and Alarm Clock

  • 2021-12-04 19:46:29
  • OfStack

There are many kinds of timing implementations in android. The common combination of Handler and Thread, handler. postDelayed, and AlarmManger to be used can all realize the execution of timing tasks, but the usage scenarios are quite different. Here, we mainly use AlarmManager to realize timing tasks.

Knowledge points involved:

1) BroadCastReceiver task reception

2) CountDownTimer countdown

3) AlertDialog task reminder

4) AlarmManager Timing Task

The requirement realized here is to shut down at 24 o'clock every day. Some equipment is a customized system, which prevents the application from being stuck when it is not shut down for a long time. When it is shut down, it gives the user a prompt and automatically shuts down if there is no operation.

Step 1 is to implement a simple layout, writing two Button, one set and one cancel in the layout
Step 2: Initialize the 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;

}

}

//  Initialization Alarm
private void initAlarm(){
pi=PendingIntent.getBroadcast(this,0,getMsgIntent(),0);
time=System.currentTimeMillis();
am= (AlarmManager) getSystemService(ALARM_SERVICE);

}

private Intent getMsgIntent(){
//AlarmReceiver  For broadcast in the following code 
Intent intent=newIntent(this,AlarmReceiver.class);
intent.setAction(AlarmReceiver.BC_ACTION);
intent.putExtra("msg"," Alarm clock on ");
return intent;

}

// Setting Timed Tasks 

private void setAlarm(){
//android Api The changes in different versions are set   Set differently 
if(Build.VERSION.SDK_INT<19){
am.set(AlarmManager.RTC_WAKEUP,getTimeDiff(),pi);
}else{
am.setExact(AlarmManager.RTC_WAKEUP,getTimeDiff(),pi);

}

}

public long getTimeDiff(){
// What is set here is that of the day 15 : 55 Minutes, pay attention to the accuracy to seconds, and the time can be set freely 
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 the execution of a timed task 
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(" Prompt ")
.setMessage(" Will be in 30 Shut down in 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)+" Shut down ");

}

@Override
public void onFinish() {
// End of countdown 
Log.i(TAG," The countdown is over! ");
alertDialog.dismiss();

// End of countdown to perform timed tasks 

//  shutdown(context);

}

};

timer.start();
}
//shoutDown Need   System permissions can be executed 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 declaration configuration file in AndroidManifest. xml:

Realize the timing task with all the codes truthfully

The bullet box requires the following permissions:


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

Related articles: