如何解决每次打开应用程序时都会触发每日可自定义的警报
在我的 Android Kotlin 应用中,我设置了一个每日重复闹钟,它的接收器向用户推送通知消息,提醒他们每天在应用中执行特定操作(他们也可以在设置中更改提醒时间)。
我在 MainActivity.onCreate
方法中进行了设置(因为我想为应用程序的所有用户设置提醒,这是我能想到的唯一可以为所有人执行的地方):
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Setup the alarm notifications
setupRepeatingalarm()
此 setupRepeatingalarm
方法采用以下形式:
fun setupRepeatingalarm(){
/**
* Create a periodic alarm
* If the user has disabled alarms we do nothing
* If they set a time we schedule for then
*/
Timber.tag(TAG).d("Setting up the repeating alarm...")
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(
applicationContext)
// What are the user's notification prefs?
val remindersEnabledKey = applicationContext.getString(R.string.reminders_enabled)
val reminderHourKey = applicationContext.getString(R.string.reminder_hour)
val reminderMinuteKey = applicationContext.getString(R.string.reminder_minute)
val remindersEnabled = sharedPreferences.getBoolean(remindersEnabledKey,false)
var reminderHour = sharedPreferences.getString(reminderHourKey,"9")
var reminderMinute = sharedPreferences.getString(reminderMinuteKey,"0")
if(reminderHour === null){
reminderHour = "9"
}
if(reminderMinute === null){
reminderMinute = "0"
}
if(!remindersEnabled){
Timber.tag(TAG).d("User does not have reminders enabled")
return
} else{
Timber.tag(TAG).d("Set alarm for $reminderHour:$reminderMinute...")
}
val notifyIntent = Intent(this,AlarmReceiver::class.java)
val notifyPendingIntent: PendingIntent = PendingIntent.getbroadcast(
this,requestCode,notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT
)
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
// Ensure we remove any existing notifications
val notificationmanager = ContextCompat.getSystemService(
this,notificationmanager::class.java
) as notificationmanager
notificationmanager.cancelNotifications()
// Set the alarm to start at approximately 9am
// Then daily at this time
val calendar: Calendar = Calendar.getInstance().apply {
timeInMillis = System.currentTimeMillis()
set(Calendar.HOUR_OF_DAY,reminderHour.toInt())
set(Calendar.MINUTE,reminderMinute.toInt())
}
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,calendar.timeInMillis,AlarmManager.INTERVAL_DAY,notifyPendingIntent
)
}
我使用共享首选项来查看此用户是否启用了提醒及其时间首选项,然后设置了 setInexactRepeating
间隔的 DAILY
闹钟。这有一个调用 AlarmReceiver
的待处理意图。我也做 notificationmanager.cancelNotifications()
以尽量避免多个现有。
问题
这似乎导致在给定的一天内超过 1 个提醒。刚刚打开应用程序似乎很快就会收到另一个通知,即使那天我已经收到了几个通知,即使我的提醒时间不是当前时间。
我想我的方法坏了,我不应该这样设置,但实现这一目标的正确方法是什么?
解决方法
我会在每次启动 setupRepeatingAlarm
时不调用 MainActivity
的位置进行设置。将其设置为设置/选项,仅在需要设置闹钟时调用它,然后再次NEVER
,直到用户设置另一个闹钟。即有一个 button
显示一个视图,允许用户选择闹钟时间,当他们完成时,使用输入的时间调用 setupRepeatingAlarm
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。