通知随机运行,而不是在设定的时间运行



我想我已经将我的闹钟管理器设置为早上7点运行,然后每隔24小时运行一次。它应该改变图像视图,然后发送通知。相反,它会在关闭或打开应用程序一两分钟后发送通知,偶尔会更改图像。有人能解释一下我哪里出错了吗?或者我怎样才能解决这个问题?

主活动-

val mIntent = Intent(this, MyReceiver::class.java)
val calendar: Calendar = Calendar.getInstance()
calendar.setTimeInMillis(System.currentTimeMillis())
calendar.set(Calendar.HOUR_OF_DAY, 7)
calendar.set(Calendar.MINUTE, 0)

val mPendingIntent = PendingIntent.getBroadcast(this, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val mAlarmManager = this
.getSystemService(Context.ALARM_SERVICE) as AlarmManager
mAlarmManager.setRepeating(
AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),86400000, mPendingIntent,
)

MyReciver——

class MyReceiver : BroadcastReceiver() {

@RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context, intent: Intent) {
val titles = arrayOf("Become inspired!", "Check out this quote!", "A new quote appeared!", "Daily quote available!")
val title = titles.random()

val notificationChannel =
NotificationChannel("My Channel", "New Quote", NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "Alerts when A new daily quote is set!"
}
val builder = NotificationCompat.Builder(context!!, "My Channel")
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(title)
.setContentText("A new daily quote is available for viewing")
with(NotificationManagerCompat.from(context)){
createNotificationChannel(notificationChannel)
notify(1, builder.build())
}
val quotes = arrayOf(R.drawable.i1, R.drawable.i2, R.drawable.i3, R.drawable.i5, 
R.drawable.i6, R.drawable.i7, R.drawable.i8, R.drawable.i9, R.drawable.i10, R.drawable.i11, R.drawable.i12)
val quote = quotes.random()
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
with(prefs.edit()) {
putInt("paintings", quote)
apply()
}
}
}

——

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.other)

val imageView = findViewById<ImageView>(R.id.paininass)
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
val quote = prefs.getInt("paintings", R.drawable.i5)
imageView.setImageResource(quote)

就像CommonsWare在评论中所说的那样,使用当前日期并将时间设置为上午7点通常会将其置于过去,并且正如AlarmManager#setRepeating文档所说:

如果设定的触发时间已经过去,立即触发告警,报警计数取决于触发时间相对于重复间隔的过去距离。

如果是过去的,你需要加上一天。你可以通过比较currentTimeMillisCalendar#getTimeInMillis来做,或者用它的before函数,或者你想怎么做。然后调用add(Calendar.DAY_OF_MONTH, 1)

最新更新