更新AlarmManager(Android)的时间

时间:2013-05-26 19:41:15

标签: android notifications alarmmanager

我使用AlarmManager在事件日期和时间显示事件的通知。 但是,当事件更新时,如何更新AlarmManager将PendingIndent发送到我的应用程序的时间?

创建事件时,将调用以下代码:

public void setOneTimeAlarm() {
        Intent intent = new Intent(this, TimerReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                intent, PendingIntent.FLAG_ONE_SHOT);

        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, day-1);
        c.set(Calendar.HOUR_OF_DAY, 18);
        c.set(Calendar.MINUTE, 00);

        long date = c.getTimeInMillis();

        mAlarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);
    }

调用的缩进是TimerReciver:

@Override
     public void onReceive(Context context, Intent intent) {
         Log.v("TimerReceiver", "onReceive called!");
         Intent notificationIntent = new Intent(context, ListTests.class);
            PendingIntent contentIntent = PendingIntent.getActivity(context,
                    123, notificationIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

            Resources res = context.getResources();
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

            long[] pattern = {0,300};

            builder.setContentIntent(contentIntent)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
                        .setTicker(res.getString(R.string.app_name))
                        .setWhen(System.currentTimeMillis())
                        .setAutoCancel(true)
                        .setVibrate(pattern)
                        .setContentTitle(res.getString(R.string.notification_title))
                        .setContentText(res.getString(R.string.notification_text));
            Notification n = builder.build();

            nm.notify(789, n);
     }

1 个答案:

答案 0 :(得分:7)

我找到了解决方案..我发现getBroadcast(Context context, int requestCode, Intent intent, int flags)的第二个参数有所不同,即使文档说明了

  

requestCode 发件人的私人请求代码(当前未使用)。

当每个事件使用请求ID时,将更新警报并为每个事件创建警报。

原因是,使用两个不同的请求代码时,filterEquals(Intent)将为false。 AlarmManager set(...)的文档说:

  

如果过去发生时间,将触发警报   立即。如果已安排此Intent的警报   (两个意图的相等性由...定义   filterEquals(Intent)),然后它将被删除并替换为此   之一。

我还将PendingIntent.FLAG_ONE_SHOT更改为PendingIndent.FLAG_CANCEL_CURRENT