闹钟管理器(Android)的更新时间

6
我将使用AlarmManager来在事件日期和时间显示通知。但是,当事件更新时,我应该如何更新AlarmManager发送PendingIntent到我的应用程序的时间呢?
当创建事件时,将调用以下代码:
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个回答

10
我找到了解决办法。原来是 getBroadcast(Context context, int requestCode, Intent intent, int flags) 的第二个参数起到了关键作用,即使文档中说:

requestCode 发送方的私有请求代码 (目前没有使用)。

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

原因是对于两个不同的请求代码,filterEquals(Intent) 将返回 false。 AlarmManager set(...) 的文档说:

如果时间已经过去,则立即触发闹钟。如果已经为此 Intent 计划了一个闹钟(两个 Intent 的相等性由 filterEquals(Intent)) 定义),则它将被删除并替换为此闹钟。

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


请你能否在修改后展示完整的代码?我认为你还应该使用 PendingIntent.FLAG_MUTABLE。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接