2
3

More than 5 years have passed since last update.

アラームを複数設定できるようにしよう

Posted at

時間を設定して、設定した時間に通知が行く機能を作っていました。
その中で、AlarmManagerの使い方を残したいと思います。

今回の実装は以下です。

val alarm = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, AlarmBroadCastReciever::class.java)
intent.putExtra("id", id)
intent.putExtra("title", title)
val pending = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT)

val info = AlarmManager.AlarmClockInfo(calendar.timeInMillis, null)
alarm.setAlarmClock(info, pending)

その中でも時間がかかったのが下記です。

val pending = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT)

ハマりポイント①:requestCodeの扱い

getBroadCastの第2引数はrequestCodeを設定します。
最初はググったら真っ先に出てくる0を指定しました。
1つのアラームセットなら問題ないですが、複数アラームを設定すると、最新のアラームしか通知されませんでした。

これは、リファレンスにあるように、requestCodeが同じだと、同じPendingIntentとみなされているからでした。

If you truly need multiple distinct PendingIntent objects active at the same time (such as to use as two notifications that are both shown at the same time), then you will need to ensure there is something that is different about them to associate them with different PendingIntents. This may be any of the Intent attributes considered by Intent#filterEquals(Intent), or different request code integers

今回は違うアラームとして認識させたいので、違うrequestCodeを設定しないといけないというものでした。

ハマりポイント②:flagsの扱い

第4引数はflagsを設定します。

こちらも同様に0を設定していました。
すると、更新しても通知で表示するtitleが更新されませんでした。

これは、FLAG_UPDATE_CURRENTをフラグに設定していなかったからでした。

こちらもリファレンスに記載がありました。

Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent

つまりは、同じrequestCodeのPendingIntentが存在する場合、そのPendingIntentをつかうが、Intentの値は更新するのが、FLAG_UPDATE_CURRENTです。

上記ハマりポイントを解消することで、思っていた動作をするようになりました。
引数の値が何を表しているのか確認することも大切ですね。

参照

リファレンス-- https://developer.android.com/reference/android/app/PendingIntent

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3