【问题标题】:android service broadcast (a reminding function)android服务广播(一个提醒功能)
【发布时间】:2012-11-22 19:40:49
【问题描述】:

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

如何完成这个功能?

我认为有两种方法:

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

第一个问题:

  1. 哪种方式正确或更好?
  2. 如何使用那个报警管理器?是不是像java中的Timer类?

【问题讨论】:

    标签: android service broadcastreceiver alarmmanager broadcast


    【解决方案1】:

    最简单和最有效的方法是使用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);
    

    【讨论】:

    • 不需要服务?当应用关闭时它可以发出通知?
    • 是的,直接来自 AlarmManager API:“注意:警报管理器适用于您希望在特定时间运行应用程序代码的情况,即使您的应用程序当前没有运行。”
    猜你喜欢
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 2014-12-25
    相关资源
    最近更新 更多