本次学习将apidemo中得两个demo:AlarmController and Alarm Service合并到一起学习
AlarmController主要实现单次alarm事件和循环alarm事件
Alarm Service 主要实现利用循环alarm事件启动service(不介绍service,后续到相关demo再深入学习)
1、AlarmController主要是利用PendingIntent 描述将要执行的Intent;PendingIntent 没有提供构造函数,需要通过static 函数getActivity(Context, int,Intent, int), getBroadcast(Context, int, Intent, int), getService(Context, int, Intent, int) 来或得想要执行的Activity,Broadcast,Service 描述。
本次demo描述了一个broadcast:
Intent intent = new Intent(AlarmControllerActivity.this, OneShotAlarm.class); PendingIntent sender = PendingIntent.getBroadcast(AlarmControllerActivity.this, 0, intent, 0);
然后执行
// Schedule the alarm! AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
其中 OneShotAlarm 被定义为一个接收者。
<receiver android:name=".app.alarm.OneShotAlarm" android:process=":remote"/>
2、同理重复的alarm事件实现 只是调用的AlarmManager的方法不同:
// Schedule the alarm! AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,10 * 1000, sender);
3、终止alarm事件 使用AlarmManager.cancel(sender)
4、最后来说一下利用alarm事件启动service,我们利用PendingIntent描述一个想要执行的service,然后通过alarm循环间隔启动该service
/ /Create an IntentSender that will launch our service, to be scheduled // with the alarm manager. mAlarmSender = PendingIntent.getService(AlarmService.this,0, new Intent(AlarmService.this, AlarmService_Service.class), 0); AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 10*1000, mAlarmSender); //stop am.cancle(mAlarmSender);
service的内容先不讨论,效果图: