Android定时任务及闹钟的实现

android中定时有很多种是实现,常见的Handler 与Thread的结合,handler.postDelayed ,以及要使用的AlarmManger 等都可以实现定时任务的执行,但是使用场景却大不相同,这里主要是怎么用AlarmManager实现定时任务。涉及知识点:

1)BroadCastReceiver任务接收

2)CountDownTimer倒计时

3)AlertDialog 任务提醒

4)AlarmManager 定时任务

这里实现的需求时每天定时24点关机,有设备是定制系统,防止长时间的不关机导致应用的卡顿,在关机时并给用户以提示,如果无操作就自动关机。

第一步是实现简单布局,在布局中写两个Button,一个设置,一个取消
第二步:初始化页面布局及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;

}

}

// 初始化Alarm

private void initAlarm(){

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

time=System.currentTimeMillis();

am= (AlarmManager) getSystemService(ALARM_SERVICE);

}

private Intent getMsgIntent(){

//AlarmReceiver 为广播在下面代码中

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

intent.setAction(AlarmReceiver.BC_ACTION);

intent.putExtra("msg","闹钟开启");

return intent;

}

//设置定时执行的任务

private void setAlarm(){

//android Api的改变不同版本中设 置有所不同

if(Build.VERSION.SDK_INT<19){

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

}else{

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

}

}

public long getTimeDiff(){

//这里设置的是当天的15:55分,注意精确到秒,时间可以自由设置

Calendar ca=Calendar.getInstance();

ca.set(Calendar.HOUR_OF_DAY,15);

ca.set(Calendar.MINUTE,55);

ca.set(Calendar.SECOND,0);

return ca.getTimeInMillis();

}

//取消定时任务的执行

private void cancelAlarm(){

am.cancel(pi);

}

}

广播主要代码

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("提示")

.setMessage("将在30秒后关机")

.setCancelable(false)

.setPositiveButton("取消",

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();

//开启倒计时,并设置倒计时时间(秒)

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) {

//倒计时提示文字

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

alertDialog.setMessage("将在"+(millisUntilFinished/1000)+"关机");

}

@Override

public void onFinish() {

//倒计时结束

Log.i(TAG,"倒计时结束!");

alertDialog.dismiss();

//倒计时结束执行定时的任务

//                shutdown(context);

}

};

timer.start();

}

//shoutDown需要 系统权限才能执行否则会提示权限异常

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);

}

}

在AndroidManifest.xml中声明配置文件中声明:

如实全部代码实现定时任务

弹框需要如下权限:

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

你可能感兴趣的:(Android笔记)