Android之AlarmManager定时器

时间:2022-08-28 00:24:29

AlarmManager实质上是一个全局定时器,是Android中常用的一种系统级别的提示服务,在指定时间或周期性启动其他组件(Activity、Service、BroadcastReceiver)。

常用方法:

void set(int type, long triggerAtMillis, PendingIntent operation)

设置在triggerAtMillis时间启动由operation参数指定的组件(如:设置一次性闹钟)。

 

void setRepeating(int type, long triggerAtMillis, long interval, PendingIntent operation)

设置在triggerAtMillis时间以interval为周期的周期性启动由operation参数指定的组件。

 

void setInexactRepeating(int type, long triggerAtMillis, long interval, PendingIntent operation)

设置一个非精确的周期性任务。

 

void cancel(PendingIntent operation)

取消任务

 

void setTime(long millis)

设置系统挂钟时间,需要android.permission.SET_TIME权限。

 

void setTimeZone(String timeZone)

设置系统的默认时区,需要android.permission.SET_TIME_ZONE权限

 

参数type用来指定定时服务的类型,参数值有:

AlarmManager.ELAPSED_REALTIME:参数triggerAtMillis需要使用SystemClock.elapseRealtime(),该alarm不会唤醒设备。如果设备处于休眠状态,则会等到设备唤醒(wake up)时触发。

AlarmManager.ELAPSED_REALTIME_WAKEUP:参数triggerAtMillis需要使用SystemClock.elapseRealtime(),如果设备处于休眠状态,会唤醒设备。

AlarmManager.RTC:参数triggerAtMillis需要使用System.currentTimeMillis(),该alarm不会唤醒设备。如果设备处于休眠状态,则会等到设备唤醒时触发。

AlarmManager.RTC_WAKEUP:参数triggerAtMillis需要使用System.currentTimeMillis(),如果设备处于休眠状态,会唤醒设备。

例子:实现1分钟循环打印消息,可以使用AlarmManager、TimeChange、Timer、Handler

public class AlarmService extends Service {

private Handler mHandler;
private Looper mLooper;
private PendingIntent mOperation;
private AlarmManager mAlarmManager;
private Timer mTimer;
private static final int ALARM = 1;
private static final int HANDLER = 2;

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
super.onCreate();
// alarm
mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
HandlerThread handlerThread = new HandlerThread("hehe");
handlerThread.start();
mLooper = handlerThread.getLooper();
mHandler = new Handler(mLooper) {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case ALARM:
int alarm = getCurrentMinute();
System.out.println("alarm:" + alarm);
setNextDetect();
break;
case HANDLER:
int handler = getCurrentMinute();
System.out.println("handler:" + handler);
mHandler.sendEmptyMessageDelayed(HANDLER, 60000);
break;
}
};
};

// timeChange
IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
registerReceiver(mTimeChangeReceiver, filter);

// timer
mTimer = new Timer();
mTimer.schedule(mTask, 0, 60000);

// handler
mHandler.sendEmptyMessage(HANDLER);
}

private void setNextDetect() {
Intent service = new Intent(this, AlarmService.class);
mOperation = PendingIntent.getService(this, 0, service,
PendingIntent.FLAG_UPDATE_CURRENT);
mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 60000, mOperation);
}

private BroadcastReceiver mTimeChangeReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_TICK)) {
int timeChange = getCurrentMinute();
System.out.println("timeChange:" + timeChange);
}
}

};

TimerTask mTask = new TimerTask() {

@Override
public void run() {
int task = getCurrentMinute();
System.out.println("task:" + task);
}
};

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHandler.sendEmptyMessage(ALARM);
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
super.onDestroy();
if (mHandler != null) {
mHandler.removeMessages(ALARM);
mHandler.removeMessages(HANDLER);
}
if (mLooper != null) {
mLooper.quit();
}
if (mAlarmManager != null) {
mAlarmManager.cancel(mOperation);
}
if (mTimeChangeReceiver != null) {
unregisterReceiver(mTimeChangeReceiver);
}
if (mTimer != null) {
mTimer.cancel();
}
if (mTask != null) {
mTask.cancel();
}
}

private int getCurrentMinute() {
return Calendar.getInstance().get(Calendar.MINUTE);
}
}