饮水提醒App仅在用户清醒时推送通知的逻辑异常排查
问题分析与修复方案
你的代码逻辑只覆盖了睡眠时段不跨午夜的场景,当睡眠时段跨越午夜(比如22:00入睡,次日6:00起床)时,判断条件会失效,导致睡眠时段仍推送通知。
核心问题
原判断条件:
if (currentTime.isAfter(userSleepTime) && currentTime.isBefore(userWakeTime)) { // 跳过通知 }
仅在userSleepTime < userWakeTime(比如22:00到23:00)时有效。但如果是跨午夜的睡眠区间(比如22:00到6:00),currentTime在22:00-24:00之间时,isBefore(userWakeTime)(6:00)为false;在0:00-6:00之间时,isAfter(userSleepTime)(22:00)为false,两种情况都不满足条件,所以不会跳过通知。
修复后的代码
修改判断逻辑,同时处理跨午夜和不跨午夜的场景:
class NeerNotificationService( private val context: Context ) : NeerNotification { private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager override fun showNotification(notificationItem: NotificationItem) { val currentTime = LocalTime.now(ZoneId.systemDefault()).truncatedTo(ChronoUnit.MINUTES) val userSleepTime = PreferencesManager(context).getSleepCycleTime(SleepCycle.SLEEP_TIME) val userWakeTime = PreferencesManager(context).getSleepCycleTime(SleepCycle.WAKE_TIME) Timber.d("User sleep time, wake time and current time") Timber.d(userSleepTime.toString()) Timber.d(userWakeTime.toString()) Timber.d(currentTime.toString()) // 修正后的睡眠时段判断逻辑 val isInSleepTime = if (userSleepTime <= userWakeTime) { // 睡眠时段不跨午夜:当前时间在入睡和起床时间之间 currentTime.isAfter(userSleepTime) && currentTime.isBefore(userWakeTime) } else { // 睡眠时段跨午夜:当前时间晚于入睡时间,或早于起床时间 currentTime.isAfter(userSleepTime) || currentTime.isBefore(userWakeTime) } if (isInSleepTime) { Timber.d("Skipping notification") return } Timber.d("Showing notification") val activityIntent = Intent(context, NeerActivity::class.java) val activityPendingIntent = PendingIntent.getActivity( context, 1, activityIntent, PendingIntent.FLAG_IMMUTABLE ) val notification = NotificationCompat.Builder(context, WATER_REMINDER_CHANNEL_ID) .setSmallIcon(R.drawable.ic_outline_water_bottle) .setContentTitle(notificationItem.title) .setContentText(notificationItem.message) .setContentIntent(activityPendingIntent) .build() notificationManager.notify(1, notification) } }
逻辑说明
- 当
userSleepTime <= userWakeTime(比如13:00-15:00午睡):判断当前时间是否在入睡和起床时间之间,是则跳过通知。 - 当
userSleepTime > userWakeTime(比如22:00-次日6:00夜间睡眠):判断当前时间是否晚于入睡时间,或者早于起床时间,满足任一条件则跳过通知。
这样就能覆盖所有睡眠时段的场景,避免在用户睡眠时推送无意义的提醒。
内容的提问来源于stack exchange,提问作者Critical AY
相关产品推荐
相关产品推荐

