6

I use AlarmManager to display a notification for an event at the event date and time. But how can I update the time the AlarmManager sends the PendingIndent to my app, when an event is updated?

When an event is created the following code is called:

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);
    }

The indent called is 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);
     }
4

1 回答 1

8

我找到了解决方案..我发现第二个参数会getBroadcast(Context context, int requestCode, Intent intent, int flags)产生影响,即使文档说

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

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

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

如果时间发生在过去,将立即触发警报。如果这个 Intent 调度已经有一个警报(两个 Intent 的相等性由 定义 filterEquals(Intent)),那么它将被删除并替换为这个。

我也改成PendingIntent.FLAG_ONE_SHOTPendingIndent.FLAG_CANCEL_CURRENT

于 2013-05-31T08:45:09.240 回答