AlarmManager定时器

首先,获取系统服务:

   

private AlarmManager mAlarmManager;
mAlarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

然后,设置定时器:

Intent intent = new Intent(this, Alerm.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, _id, intent, 0);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), mPendingIntent);

intent用于指定传递的地方,本例指跳转去Alerm.class类中。

PendingIntent是指时间到了的时候需要做的事情。本例是使用getActivity,即打开一个Activity;还可以用getBroadcast或者getService的方式,具体作用,即发广播或开启服务。PendingIntent中的_id参数是用来区分AlarmManager,即如果有两个AlarmManager存在,即他们两个的_id相应的值会不一样。

set语句是用来设置定时事件。第一个参数有四种模式:ELAPSED_REALTIME (指定时间间隔操作,不唤醒屏幕)、ELAPSED_REALTIME_WAKEUP(指定时间间隔操作且唤醒屏幕)、RTC (指定时间操作,即闹钟,不唤醒屏幕)、RTC_WAKEUP(指定时间操作,唤醒屏幕)。第二个参数会根据第一个参数的选择有所区别;比如本例,是选择RTC_WAKEUP,然后第二个参数是System.currentTimeMillis(),所以会立刻执行,相应改为ELAPSED_REALTIME_WAKEUP,第二个参数需要变更为0。

最后,取消定时器:

mAlarmManager.cancel(pendingIntent);

 取消pendingIntent的定时器。

若对同一个_id的闹钟进行操作,则最后的一个操作有效。

猜你喜欢

转载自tracy061.iteye.com/blog/1847797