25

alarmManager特定の時間にユーザーに通知を送信するために使用しているものがあります。複数のアラームがあるため、作成して一意のIDを指定する保留中のインテントが複数ありますが、保留中のインテントをすべて取得してキャンセルする必要がある場合があります。これにより、アラームをリセットできます。私はこれを試してみましたが、それでも正しく理解できないようですので、いくつか質問があります。

これはあなたが正しく取得してキャンセルする方法PendingIntentですか?

Intent intent = new Intent(con, AppointmentNotificationReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(con, id, intent,
        PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) con.getSystemService(Context.ALARM_SERVICE);
am.cancel(sender);

インテントは、元の保留中のインテント(エクストラおよびすべて)のインテントと正確に一致する必要がありますか?

フラグは元の保留中のインテントのPendingIntentフラグと一致する必要がありますか?

4

2 に答える 2

60

保留中のインテントを実際に「取得」しないことがわかりました...最初に作成したときとまったく同じように(インテントも)再作成してから、AlarmManagerのキャンセル関数に渡す必要があります。したがって、私が最初に作成した方法である限り、私が投稿した上記のコードは実際には正しくありません。うまくいけば、誰かがこれが役立つと思うでしょう。

于 2010-12-03T21:47:34.037 に答える
1

アラームの作成とキャンセルのテスト実装の例があります。

    public void setTHEalarm(Calendar aCalendarToAlarm) {
    int id;
    Intent intent;
    PendingIntent pendingIntent;
    AlarmManager alarmManager;

    //I create an unique ID for my Pending Intent based on fire time of my alarm:

    id = Integer.parseInt(String.format("%s%s%s%s",

            aCalendarToAlarm.get(Calendar.HOUR_OF_DAY),
            aCalendarToAlarm.get(Calendar.MINUTE),
            aCalendarToAlarm.get(Calendar.SECOND),
            aCalendarToAlarm.get(Calendar.MILLISECOND))); //HASH for ID

    intent = new Intent(this,AlarmReceiver.class);
    intent.putExtra("id",id); //Use the id on my intent, It would be usefull later.

    //Put the id on my Pending Intent:
    pendingIntent = PendingIntent.getBroadcast(this,id,intent,0);
    alarmManager = (AlarmManager)

            this.getSystemService(Context.ALARM_SERVICE);


    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,aCalendarToAlarm.getTimeInMillis(),CustomDate.INTERVAL_MINUTE,pendingIntent);


    Log.w(TAG+" Torrancio","Created alarm id: "
            +id+" -> "
            +CustomDate.dateToHumanString(aCalendarToAlarm.getTime()));

    //Keep a reference in a previously declared field of My Activity (...)
    this.idSaved = id;

}

//Now for canceling
public void setCancel() {
    int id;
    Intent intent;
    PendingIntent pendingIntent;
    AlarmManager alarmManager;

    id = this.idSaved;
    intent =  new Intent(this,AlarmReceiver.class);
    intent.putExtra("id",id);
    pendingIntent = PendingIntent.getBroadcast(this,id,intent,PendingIntent.FLAG_CANCEL_CURRENT);

    //Note I used FLAG_CANCEL_CURRENT 

    alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);

    Log.w(TAG+" Torrancio","Canceled->"+id);


}

3つのものが必要です、

  • 同じタイプのインテント(この場合、AlarmManagerについて話します)。
  • 同じPendingIntentID(IDの参照を保持し、何らかの方法で保存します)。
  • 正しいフラグ(キャンセルの場合はFLAG_CANCEL_CURRENT、必要はありません。また、保留中のインテントを作成したときに使用したものである必要もありません[カルセルにはキャンセルフラグを使用しますが、作成はしません。 ])

詳細については、こちらをご覧ください

それが役に立てば幸い。

于 2016-08-19T16:06:14.457 に答える