【问题标题】:the new notification cancel the old one新通知取消旧通知
【发布时间】:2016-03-25 20:47:37
【问题描述】:

在我的应用程序中,用户必须添加多个通知,但我的问题是当用户添加新通知时,旧通知被删除或取消。我认为它来自 pendingIntent,我应该使用什么适当的标志?

这是我的一些代码:

Calendar calendar = Calendar.getInstance();
    Intent intent;
    PendingIntent pendingIntent;
    AlarmManager alarmManager;
    long futureInMillis;
    switch (type) {
        case SCHEDULE_BY_DAYS:
            intent = new Intent(this, NotificationReceiver.class);
            intent.putExtra(NotificationReceiver.NOTIFICATION_ID, 1);
            intent.putExtra(NotificationReceiver.NOTIFICATION, getNotification("WAKEP UP days !!"));
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            break;
        case SCHEDULE_BY_HOURS:

            futureInMillis = SystemClock.elapsedRealtime() + (value * 600000);
            intent = new Intent(this, NotificationReceiver.class);
            intent.putExtra(NotificationReceiver.NOTIFICATION_ID, 1);
            intent.putExtra(NotificationReceiver.NOTIFICATION, getNotification("WAKEP UP hours"));
            pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
            break;

【问题讨论】:

    标签: android notifications alarmmanager android-pendingintent


    【解决方案1】:

    如果您为每个 PendingIntent 指定不同的 requestCode,则通知不会相互取消。

    PendingIntent.getBroadcast(this, unique_code, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    编辑

    int uniqueCode = sharedPreferences.getInt("unique_code",0) + 1;
    sharedPreferences.edit().putInt("unique_code",uniqueCode).apply()
    

    【讨论】:

    • 我不明白,唯一代码将包含什么?
    • 只是向上数。第一个通知得到 1,第二个得到 2,等等。它必须是唯一的,这是确保这一点的最简单方法。
    • 你能给我一个示例代码来了解它是如何工作的吗?因为它还必须取消相同的 id。
    • 我已经提供了关于它如何工作的代码。但是您在问题中表示您希望取消这些通知,为什么现在要求取消?
    • 好的,在我的代码中,我用 0 指定所有请求,可能是因为它被替换了。
    【解决方案2】:

    您需要在应用的 build.gradle 文件中添加如下所示的依赖项:

    Java:实现“androidx.preference:preference:1.1.1”

    Kotlin:实现“androidx.preference:preference-ktx:1.1.1”

    然后在你的片段中做这样的事情。如果您在活动中,则不需要 requireActivity()。

    `
     val sharedPreferences = requireActivity().getSharedPreferences("Notification_data", Context.MODE_PRIVATE)
        val customRequestCode = sharedPreferences.getInt("customRequestCode", 0) + 1
        sharedPreferences.edit().putInt("customRequestCode", customRequestCode).apply()
    `
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多