Android:通知取消它重复闹钟

时间:2017-05-17 18:11:45

标签: android notifications alarmmanager

我希望我的通知取消它自己的重复闹钟。但是,我甚至不知道如何在创建之前传递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,该通知是其中的一部分。有什么方法可以欺骗系统吗?

1 个答案:

答案 0 :(得分:1)

使用AlarmManager.cancel()cancel特定alarm并使用用于创建闹钟的PendingIntent。当然,您应该使用之前使用过的requestCodeNOTIFY_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在通知面板上MainActivity时会click

希望这会有所帮助〜