我想在我的应用程序中有一个提醒功能(通过设置提醒时间),使用通知。我知道可能有使用服务,广播和警报器,
如何完成此功能?
我认为有两种方法:
- 使用服务,通知正在服务
- 使用服务发送广播,通知在广播接收器中
第一个问题:
- 哪种方式是正确的或更好的?
- 如何使用那个警报管理器? 这类似于Java中的Timer Class吗?
最简单和最有效的方法是使用AlarmManager进行提醒之类的操作。您将需要制作一个接收警报的BroadCastReceiver。您的接收方可以发出通知,因为接收方的onReceive()
方法也接受Context
参数。要发出警报,您必须获取 AlarmManager 类的实例,使用您需要的内容制作一个待处理意图,然后实际设置警报。
设置闹钟的示例代码
Intent intent = new Intent (this, AlarmBroadcastReceiver.class);
PendingIntent pendIntent = PendingIntent.getBroadcast(this, id, intent, //makes a new intent
PendingIntent.FLAG_UPDATE_CURRENT); //only updates PendingIntent, does not recreate
AlarmManager alarmManager = (AlarmManager) getSystemService (Context.ALARM_SERVICE);
alarmManager.cancel(pendIntent); //used to cancel if previously active
alarmManager.set(AlarmManager.RTC_WAKEUP, timeToExec, //sets the alarm to exectute once
pendIntent);