【Kotlin】Alarm Managerで特定日時で処理を実行する

Alarm Managerを使うと指定した時間に処理を実行できます。

指定した時間AM8時半にToastを表示するアプリを作ってみました。

    fun setAlarm(v: View){

        // Set the alarm to start at 8:30 a.m.
        val calendar: Calendar = Calendar.getInstance().apply {
            timeInMillis = System.currentTimeMillis()
            set(Calendar.HOUR_OF_DAY, 8)
            set(Calendar.MINUTE, 30)
        }

        //BRを指定する
        val intent = Intent(
            applicationContext,
            AlarmReceiver::class.java
        )
        val pending = getBroadcast(
            applicationContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        // アラームをセットする
        val am = getSystemService(ALARM_SERVICE) as AlarmManager
        am.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pending)

        Toast.makeText(
            applicationContext,
            "Set Alarm ", Toast.LENGTH_SHORT
        ).show()
    }

実行するとインテントで指定したブロードキャスト・レシーバーが起動します。

上記のコードでは1つのアラームしかセットできません。

getBroadcastの2つ目の引数を0で固定していますが、ユニークな値にすると複数のアラームをセットすることができます。

https://stackoverflow.com/questions/8469705/how-to-set-multiple-alarms-using-alarm-manager-in-android

ちなみに、1分ごとに繰り返す場合には、以下のようにします。

am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, 1000 * 60, pending)

消費電力の問題で、繰り返しのインターバルを1分以内にすると警告が出ます。

ブロードキャストではトーストを表示するのみです。

class AlarmReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        // This method is called when the BroadcastReceiver is receiving an Intent broadcast.
        Toast.makeText(context,"hoge", Toast.LENGTH_LONG).show()
    }
}

ABOUTこの記事をかいた人

個人アプリ開発者。Python、Swift、Unityのことを発信します。月間2.5万PVブログ運営。 Twitter:@yamagablog