[Android] 003. AlarmManager(バックグラウンド処理)

バックグラウンド処理の方法はいろいろありますがここではAlarmManagerを簡単にためしてみました
developerの実装例とほぼ同じですがブロードキャストレシーバの処理がはしょられてたりするのでコピペでサクッと確認できるようにまとめました

バックグラウンド処理については以下を参照してください
https://developer.android.com/guide/background?hl=ja
AlarmManagerについては以下
https://developer.android.com/training/scheduling/alarms?hl=ja
AlarmManagerで使用するブロードキャストレシーバについては以下
https://developer.android.com/guide/components/broadcasts?hl=ja
https://developer.android.com/guide/topics/manifest/receiver-element?hl=ja

BroadcastReceiver

とりあえずBroadcastReceiverに処理が渡ったら通知とToastを表示するを実装してAndroidManifestに登録します

internal class AlarmBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        var text = "alarm!"
        Toast.makeText(context, text, Toast.LENGTH_LONG).show()
        sendNotification(context, "AlarmManager", text)
    }

    private fun sendNotification(context: Context, title: String, text: String) {
        val channelId = "channel_id"
        val channel = NotificationChannel(
            channelId,
            "channel_name",
            NotificationManager.IMPORTANCE_DEFAULT).apply {
            description = "channel description"
            setShowBadge(true)
        }

        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.createNotificationChannel(channel)

        val builder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle(title)
            .setContentText(text)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)

        var notificationId = 1
        with(NotificationManagerCompat.from(context)) {
            if (ActivityCompat.checkSelfPermission(
                    context,
                    Manifest.permission.POST_NOTIFICATIONS
            ) != PackageManager.PERMISSION_GRANTED) {
                return
            }
            notify(notificationId, builder.build())
        }
    }
}
<manifest>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <application>
        <receiver
            android:name=".AlarmBroadcastReceiver"
            android:process=":remote" />
    </application>
</manifest>

AlarmManager

ボタンを押して20秒後に実行されます

var context = LocalContext.current
var alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
var alarmIntent: PendingIntent = Intent(context, AlarmBroadcastReceiver::class.java).let { intent ->
    PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
}

Button(onClick = {
    alarmMgr?.set(
        AlarmManager.ELAPSED_REALTIME_WAKEUP,
        SystemClock.elapsedRealtime() + 20 * 1000,
        alarmIntent
    )
}) {
    Text("Start")
}

実行

通知を送信するのでアプリインストール後アプリの通知をONにしてください
startボタンを押した後アプリをバックグラウンドに遷移させて20秒後に通知が発生することを確認してください
※ フォアグラウンドでも通知は発生します

デバイスをロック画面に遷移させても動作することも確認してみてください
※ OSの通知の設定でロック画面に通知を表示する設定をしてください


Android Studio Giraffe 2022.3.1 built on June 29, 2023