75

我正在设置这样的警报:

alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingEvent);

我有兴趣删除之前设置的所有警报,清除它们。

有没有办法让我这样做或获取当前设置的所有警报,以便我可以手动删除它们?

4

5 回答 5

87

您不必一直引用它。只需定义一个新的 PendingIntent 就像您在创建它时定义的一样。

例如:

如果我创建了一个 PendingIntent 以由 AlarmManager 触发,如下所示:

Intent alarmIntent = new Intent(getApplicationContext(), AlarmBroadcastReceiver.class);
alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
alarmIntent.setAction(String.valueOf(alarm.ID));
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

PendingIntent displayIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);

alarmManager.set(AlarmManager.RTC_WAKEUP, alarmDateTime, displayIntent);

然后在你的其他代码(甚至是另一个活动)的某个地方,你可以这样做来取消:

Intent alarmIntent = new Intent(getApplicationContext(), AlarmBroadcastReceiver.class);
alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
alarmIntent.setAction(String.valueOf(alarm.ID));
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

PendingIntent displayIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, 0);

alarmManager.cancel(displayIntent);

这里重要的是使用完全相同的数据和操作以及其他标准设置 PendingIntent 以及此处所述http://developer.android.com/reference/android/app/AlarmManager.html#cancel%28android.app .PendingIntent%29

于 2012-02-02T11:12:54.640 回答
66

您需要创建待处理的意图,然后将其取消

 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent updateServiceIntent = new Intent(context, MyPendingIntentService.class);
    PendingIntent pendingUpdateIntent = PendingIntent.getService(context, 0, updateServiceIntent, 0);

    // Cancel alarms
    try {
        alarmManager.cancel(pendingUpdateIntent);
    } catch (Exception e) {
        Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
    }
于 2010-11-30T16:51:25.900 回答
20

要取消警报,您需要重新创建相同的 PendingIntent 并传递相同的请求代码。

因此,我创建了一个 AlarmUtils 来帮助我将所有请求代码保存在首选项中,以便将来在需要时取消它。您只需要使用以下类并调用以下方法:

  • addAlarm添加新警报并传递请求代码。
  • cancelAlarm要删除警报,您需要重新创建相同的
    Intent 并传递相同的请求代码。
  • hasAlarm要验证是否添加了该警报,您需要重新创建相同的 Intent 并传递相同的请求代码。
  • cancelAllAlarms删除所有设置的警报。

我的 AlarmUtils

public class AlarmUtils {

    private static final String sTagAlarms = ":alarms";

    public static void addAlarm(Context context, Intent intent, int notificationId, Calendar calendar) {

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }

        saveAlarmId(context, notificationId);
    }

    public static void cancelAlarm(Context context, Intent intent, int notificationId) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.cancel(pendingIntent);
        pendingIntent.cancel();

        removeAlarmId(context, notificationId);
    }

    public static void cancelAllAlarms(Context context, Intent intent) {
        for (int idAlarm : getAlarmIds(context)) {
            cancelAlarm(context, intent, idAlarm);
        }
    }

    public static boolean hasAlarm(Context context, Intent intent, int notificationId) {
        return PendingIntent.getBroadcast(context, notificationId, intent, PendingIntent.FLAG_NO_CREATE) != null;
    }

    private static void saveAlarmId(Context context, int id) {
        List<Integer> idsAlarms = getAlarmIds(context);

        if (idsAlarms.contains(id)) {
            return;
        }

        idsAlarms.add(id);

        saveIdsInPreferences(context, idsAlarms);
    }

    private static void removeAlarmId(Context context, int id) {
        List<Integer> idsAlarms = getAlarmIds(context);

        for (int i = 0; i < idsAlarms.size(); i++) {
            if (idsAlarms.get(i) == id)
                idsAlarms.remove(i);
        }

        saveIdsInPreferences(context, idsAlarms);
    }

    private static List<Integer> getAlarmIds(Context context) {
        List<Integer> ids = new ArrayList<>();
        try {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            JSONArray jsonArray2 = new JSONArray(prefs.getString(context.getPackageName() + sTagAlarms, "[]"));

            for (int i = 0; i < jsonArray2.length(); i++) {
                ids.add(jsonArray2.getInt(i));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ids;
    }

    private static void saveIdsInPreferences(Context context, List<Integer> lstIds) {
        JSONArray jsonArray = new JSONArray();
        for (Integer idAlarm : lstIds) {
            jsonArray.put(idAlarm);
        }

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(context.getPackageName() + sTagAlarms, jsonArray.toString());

        editor.apply();
    }
}
于 2017-02-15T01:47:17.350 回答
0

如果将 PendingIntent id 保存在 SharedPreference 或 db 中,当Android 重启你的包强制停止时,你会得到错误的值

您可以将之前的所有 PendingIntent 保存到另一个新的 PendingIntent,然后再取消所有

例如

    void createSomeAlarmAndSave() {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(this, MyReceiver.class).setAction(ACTION_XXX), 0);
        getSystemService(AlarmManager.class).setInexactRepeating(AlarmManager.RTC_WAKEUP, 1000 * 60 * 15, 1000 * 60 * 15, pendingIntent);

        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 1, new Intent(this, MyReceiver.class).setAction(ACTION_XXX), 0);
        getSystemService(AlarmManager.class).setInexactRepeating(AlarmManager.RTC_WAKEUP, 1000 * 60 * 20, 1000 * 60 * 20, pendingIntent1);

        PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 2, new Intent(this, MyReceiver.class).setAction(ACTION_XXX), 0);
        getSystemService(AlarmManager.class).setInexactRepeating(AlarmManager.RTC_WAKEUP, 1000 * 60 * 25, 1000 * 60 * 25, pendingIntent2);

        //save all previous PendingIntent to another new PendingIntent
        PendingIntent.getBroadcast(this, 0, new Intent(this, MyReceiver.class).putExtra("previous", new PendingIntent[]{pendingIntent, pendingIntent1, pendingIntent2}), PendingIntent.FLAG_UPDATE_CURRENT);
    }

取消所有之前的 PendingIntent

    void cancelAllPreviousAlarm() {
        //acquire the dedicated PendingIntent
        PendingIntent pendingIntentAllPrevious = PendingIntent.getBroadcast(this, 0, new Intent(this, MyReceiver.class), PendingIntent.FLAG_NO_CREATE);
        if (pendingIntentAllPrevious != null) {
            try {
                pendingIntentAllPrevious.send(this, 0, null, new PendingIntent.OnFinished() {
                    @Override
                    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, String resultData, Bundle resultExtras) {
                        for (Parcelable parcelable : intent.getParcelableArrayExtra("previous")) {
                            //alarm will cancel when the corresponding PendingIntent cancel
                            ((PendingIntent) parcelable).cancel();
                        }
                    }
                }, null);
                pendingIntentAllPrevious.cancel();
            } catch (PendingIntent.CanceledException e) {
                e.printStackTrace();
            }
        }
    }
于 2020-12-11T08:27:59.830 回答
0

如果您重新创建 PendingIntent:

PendingIntent pendingIntent = PendingIntent.getBroadcast(
            context, 0, newIntent, PendingIntent.FLAG_CANCEL_CURRENT);
于 2021-04-19T06:41:05.600 回答