如何使用警报管理器进行通知?

时间:2013-09-07 23:12:39

标签: android database notifications alarmmanager

在我的项目中,我有一个包含年,月,日,小时,分钟的数据库。对于此数据库中的每一行,我想要及时为用户提供标题和描述的通知,即该行中描述的,但是当我使用NotificationManager时,当我向数据库添加新时间时,它会立即激活。我读了这篇文章:Alarm Manager Example,关于Alarm Manager示例,但我仍然无法理解,如何将它用于通知,因为当我尝试使用时,没有任何反应。如果有人可以帮助我,我会很高兴。

1 个答案:

答案 0 :(得分:1)

我的消息不清楚。如果您尝试在特定时间启动通知,这是一种方法。使用2项服务;一个服务(您可以将其称为SetAlarmService)来读取您的数据库并设置一个待处理的意图,以便在特定时间使用AlarmManager启动。您可以通过调用getSystemService(Context.ALARM_SERVICE);来获取实例。您应该设置您的待定意图以启动另一项服务(您可以将其命名为NotifyService),该服务只会在启动后立即发出通知。

编辑:这是一个简单的例子,请参阅文档以获取参数说明等。

public class AlarmService extends Service {

    Time time;
    AlarmManager alarmMan;

    @Override
    public void onCreate() {
        alarmMan = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        time = new Time();
    }

    @Override
    public int onStartCommand(Intent intent, int startID, int flags) {
        time.setToNow();
        alarmMan.set(AlarmManager.RTC_WAKEUP, time.toMillis(false)+(10*1000), getPIntent());
        time = null;
    }

   public PendingIntent getPIntent() {
        Intent startIntent = new Intent(this, NotifyService.class);
        startIntent.setAction(com.berrmal.remindme.NotifyService.ACTION_SEND_NOTIFICATION);
        PendingIntent pIntent = PendingIntent.getService(this, 0, startIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        return pIntent;
    }

我从活动中启动此服务,您可以按照您想要的任何方式执行此操作。 NotifyService.class是我写的另一个服务,只是立即发布粘性通知,我不打算显示,因为听起来你已经知道如何使用NotificationManager。这里的关键是10 * 1000,即未来警报将被激活多少毫秒,以及通知将在什么时间出现。你可以从一个文件等中读取它。在这个例子中,我现在只计算10000毫安。 RTC_WAKEUP标志是您想要阅读的4个标志之一,它们使警报略有不同。希望有所帮助。