2
我想通过通知在我的应用中使用提醒功能(通过设置提醒时间)。并且我知道有可能使用服务,广播和报警器,安卓服务广播(提醒功能)
我该如何完成此功能?
我认为有两种方式:
- 使用该服务,该通知是在服务
- 使用该服务来发送广播,通知是在广播接收器
的第一个问题:
- 哪种方式合适或更好?
- 如何使用该警报管理器?是像java中的Timer类吗?
我想通过通知在我的应用中使用提醒功能(通过设置提醒时间)。并且我知道有可能使用服务,广播和报警器,安卓服务广播(提醒功能)
我该如何完成此功能?
我认为有两种方式:
的第一个问题:
最简单和最有效的方法是使用AlarmManager进行提醒等操作。您需要制作一个BroadCastReceiver接收您的闹钟。您的接收器可以制作notification,因为接收器的onReceive()
方法也需要参数Context
。要进行报警,您必须获取AlarmManager类的实例,根据需要创建一个PendingIntent,然后实际设置报警。
用于设置报警示例代码
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);
不需要的服务?它可以在应用程序关闭时发出通知? – Joey
是的,直接来自AlarmManager API:“注意:Alarm Manager适用于希望在特定时间运行应用程序代码的情况,即使您的应用程序当前未在运行。” –
我明白了..非常感谢! – Joey