android - Kotlin 中的通知每天在同一时间重复
问题描述
我发现的其他 Stackoverflow 代码都不起作用。要么是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>
推荐阅读
- excel - VBA - 在自动过滤器中排除通配符值?
- sql - SQL 语句唯一 ID,然后按唯一 ID 分组并计算不同的其他 ID 组
- swift - 统一日志记录、StaticString、CustomStringConvertible 和描述的问题
- html - Pandoc:将 Markdown 转换为 HTML *无需*任何 HTML 属性
- java - 预约班
- mysql - SQL - 两个(连接的)表的合并竞争列表
- java - Kafka Streams 到主题
- excel - FIFO老化模拟
- centos6 - 在 CentOS 6 上更新 libcurl 后 YUM 损坏
- bash - Shell,复制名称相似的文件