闹钟的原理可用下面我自己画的一幅图来概括:(不对的地方,尽管吐槽)
我们来看看新建闹钟到闹钟响铃的步骤:
1、新建一个闹钟:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
// 获得AlarmManager实例
final AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
// 实例化Intent
Intent intent = new Intent();
// 设置Intent action属性
intent.setAction("com.test.BC_ACTION");
intent.putExtra("msg", "该去开会啦!");
// 实例化PendingIntent
final PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0,
intent, 0);
// 获得系统时间
final long time = System.currentTimeMillis();
am.set(AlarmManager.RTC_WAKEUP, time+5000, sender);//5秒后闹铃
// 设置按钮单击事件
setBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 重复提示,从当前时间开始,间隔5秒
am.setRepeating(AlarmManager.RTC_WAKEUP, time,
5 * 1000, pi);
}
});
|
1
2
3
4
5
|
<receiverandroid:name="MyReceiver">
<intent-filter>
<actionandroid:name="com.test.BC_ACTION"/>
</intent-filter>
</receiver>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//操作:发送一个广播,广播接收后Toast提示定时操作完成
Intent intent =newIntent(Main.this, alarmreceiver.class);
intent.setAction("short");
PendingIntent sender=
PendingIntent.getBroadcast(Main.this,0, intent,0);
//设定一个五秒后的时间
Calendar calendar=Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND,5);
AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
//或者以下面方式简化
//alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000, sender);
Toast.makeText(Main.this,"五秒后alarm开启", Toast.LENGTH_LONG).show();
|
1
2
3
4
5
6
7
8
9
10
11
12
|
Intent intent =new Intent(Main.this, alarmreceiver.class);
intent.setAction("repeating");
PendingIntent sender=PendingIntent
.getBroadcast(Main.this, 0, intent, 0);
//开始时间
long firstime=SystemClock.elapsedRealtime();
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
//5秒一个周期,不停的发送广播
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP
, firstime, 5*1000, sender);
|
1
2
3
4
5
6
|
Intent intent =newIntent(Main.this, alarmreceiver.class);
intent.setAction("repeating");
PendingIntent sender=PendingIntent
.getBroadcast(Main.this,0, intent,0);
AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
alarm.cancel(sender);
|
AlarmManager还将闹钟分为五种类型:
1
|
public staticfinalintELAPSED_REALTIME
|
1
|
publicstaticfinalintELAPSED_REALTIME_WAKEUP
|
1
|
public static final int RTC
|
1
|
publicstaticfinalintRTC_WAKEUP
|
1
|
PublicstaticfinalintPOWER_OFF_WAKEUP
|
综上所述,感觉AlarmManage和NotificationManager差不多,NotificationManager例子请见文章http://my.oschina.net/helu/blog/141728
我的博客其它文章列表
http://my.oschina.net/helu