Notification in Kotlin repeating every day at the same time

Viewed 2534

None of the other Stackoverflow code I found works. All is either Java, or I'm too dumb to make it work.

How to fire notification at the same time every day? So basic thing and I can't find anything for Kotlin.

1 Answers

Use this code to schedule showing notification each day at 22:00 (or any other hour in HOUR_TO_SHOW_PUSH):

private val alarmManager = context.getSystemService(ALARM_SERVICE) as AlarmManager
private val alarmPendingIntent by lazy {
    val intent = Intent(context, AlarmReceiver::class.java)
    PendingIntent.getBroadcast(context, 0, intent, 0)
}
private const val HOUR_TO_SHOW_PUSH = 22

fun schedulePushNotifications() {
    val calendar = GregorianCalendar.getInstance().apply {
        if (get(Calendar.HOUR_OF_DAY) >= HOUR_TO_SHOW_PUSH) {
            add(Calendar.DAY_OF_MONTH, 1)
        }

        set(Calendar.HOUR_OF_DAY, HOUR_TO_SHOW_PUSH)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }

    alarmManager.setRepeating(
        AlarmManager.RTC_WAKEUP,
        calendar.timeInMillis,
        AlarmManager.INTERVAL_DAY,
        alarmPendingIntent
    )
}

It will trigger BroadcastReceiver called AlarmReceiver, so you'll have to implement it too:

class AlarmReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        showPushNotification() // implement showing notification in this function
    }
}

Don't forget to register it in your AndroidManifest.xml:

<receiver android:name="com.your-package-name.AlarmReceiver" android:enabled="true"/>

Also note that to schedule these notifications you have to call schedulePushNotifications(), meaning that the app has to be launched at least once after each reboot. If you want your notifications to be shown after a reboot without launching your app, consider implementing BootReceiver that will be triggered immediately after reboot:

class BootReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == "android.intent.action.BOOT_COMPLETED") {
            schedulePushNotifications()
        }
    }
}

Don't forget to register it in AndroidManifest.xml too:

<receiver android:name="com.your-package-name.BootReceiver" android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
</receiver>
Related