首页 > 解决方案 > Kotlin 中的通知每天在同一时间重复

问题描述

我发现的其他 Stackoverflow 代码都不起作用。要么是Java,要么我太笨了,无法让它工作。

如何每天在同一时间触发通知?如此基本的东西,我找不到 Kotlin 的任何东西。

标签: androidandroid-studiokotlinandroid-notifications

解决方案


使用此代码安排在每天 22:00(或 中的任何其他时间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
    )
}

它会触发BroadcastReceiver被调用AlarmReceiver,所以你也必须实现它:

class AlarmReceiver : BroadcastReceiver() {

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

不要忘记在你的 AndroidManifest.xml 中注册它:

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

另请注意,要安排这些通知,您必须调用schedulePushNotifications(),这意味着应用程序必须在每次重新启动后至少启动一次。如果您希望在重启后显示通知而不启动您的应用程序,请考虑实施BootReceiver将在重启后立即触发的通知:

class BootReceiver : BroadcastReceiver() {

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

不要忘记在 AndroidManifest.xml 中注册它:

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

推荐阅读