【问题标题】:Android: Notification cancels it's repeating alarmAndroid:通知取消它的重复警报
【发布时间】:2017-05-17 18:11:45
【问题描述】:

我希望我的通知取消它自己的重复警报。但是,我什至不知道如何在创建之前传递 pendingIntent(以便稍后取消)。

在这里设置警报:

public class Schedule extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wakeLock.acquire();

        //next is notification code. //

        ...

        //create intent.
        Intent notificationIntent = new Intent(context, MainActivity.class);

        PendingIntent contentIntent = PendingIntent.getActivity(context,
                NOTIFY_ID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        ...

        ////
        wakeLock.release();
    }

    public void setAlarm(Context context) {

        ...

        Intent intent = new Intent(context, Schedule.class);
        intent.putExtra("DELAY", delay);
        intent.putExtra("NOTIFICATION_ID", id);
        intent.putExtra("TITLE_TEXT", titleText);
        intent.putExtra("BIG_TEXT", bigText);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 * 60 * delay, 1000 * 60 * delay, pendingIntent);
    }
}

关键问题是我想取消通知点击时的重复警报(onRecieve方法中的意图),但取消警报需要pendingIntent,通知是其中的一部分。有什么办法欺骗系统?

【问题讨论】:

    标签: android notifications alarmmanager


    【解决方案1】:

    使用AlarmManager.cancel()cancel 特定alarm 并使用用于创建警报的相同PendingIntent。当然,你应该使用之前使用的相同的requestCode(NOTIFY_ID)。

    试试这个:

    Intent intent = new Intent(this, Schedule.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, NOTIFY_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    
    alarmManager.cancel(pendingIntent);
    

    将此代码部分添加到您的 MainActivty 的 onCreate() 方法中,因为您的 notification 将在通知面板中的 click 上指向 MainActivity

    希望对你有帮助~

    【讨论】:

    • 你好 :) 我已经在这里看到了这个答案(当然我在问之前尝试过用谷歌搜索)。但问题是方法 cancel() 需要在通知传递给它之后创建的 pendingIntent。或者我可以简单地创建具有相同 ID 的pendingIntent 以便能够取消它?如果是这样,那就太棒了。我会尽快尝试,非常感谢:)
    • 这不起作用:(我按照你说的做了,点击后通知一直显示。
    • 确保您使用相同的通知 ID 来取消通知。点击通知时是否要从面板中删除通知?
    • 现在可以了。谢谢伙计!然而,这个问题很奇怪。我有 if-else 开关,它总是触发默认的“假”。使用 if (true) 并且它有效:D 你应该获得一枚奖牌。非常感谢你:)
    • 因为您有投票的特权。如果我的回答有帮助,请也投赞成票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多