2

我想在我的应用程序中有一个提醒功能(通过设置提醒时间),使用通知。而且我知道可能使用过服务,广播和警报管理器,

我怎样才能完成这个功能?

我认为有两种方法:

  1. 使用服务,通知服务中
  2. 使用服务发送广播,通知在broadcastReceiver

第一个问题:

  1. 哪种方式正确或更好?
  2. 如何使用该警报管理器?这像java中的Timer类吗?
4

1 回答 1

0

最简单和最有效的方法是将AlarmManager用于提醒之类的事情。您将需要制作一个接收警报的广播接收器。您的接收者可以发出通知,因为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);
于 2012-12-05T02:52:07.197 回答