Kotlin 中的通知每天在同一时间重复

Notification in Kotlin repeating every day at the same time

我发现的其他 Whosebug 代码的

None 有效。全部都是Java,或者我太笨了,无法让它发挥作用。

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

使用此代码安排每天在 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>