package com.focusbox.app.service import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import android.os.SystemClock import android.widget.RemoteViews import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.focusbox.app.R import com.focusbox.app.ui.MainActivity import com.focusbox.app.util.Dates /** * 通知构建集中在这里:常驻计时通知 + 结束提醒,两条通道用途不同。 * * 常驻通知的时间交给系统 Chronometer 渲染,而不是每秒重发一条通知: * 锁屏与息屏时第三方进程常被限流,自己刷新文本会"冻住", * 系统级计时器的走时不受这个限制。 */ object Notif { const val CHANNEL_TIMER = "timer_ongoing" const val CHANNEL_ALERT = "timer_alert" const val ID_ONGOING = 1001 private const val ID_ALERT = 1002 fun createChannels(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return val nm = context.getSystemService(NotificationManager::class.java) ?: return val ongoing = NotificationChannel( CHANNEL_TIMER, context.getString(R.string.notif_channel), NotificationManager.IMPORTANCE_LOW, ).apply { description = context.getString(R.string.notif_channel_desc) setShowBadge(false) enableVibration(false) setSound(null, null) } nm.createNotificationChannel(ongoing) // 提醒通道交给我们自己播放声音与振动,这里保持静默,避免"响两遍"。 val alert = NotificationChannel( CHANNEL_ALERT, "计时结束提醒", NotificationManager.IMPORTANCE_HIGH, ).apply { enableVibration(false) setSound(null, null) setShowBadge(true) } nm.createNotificationChannel(alert) } private fun contentIntent(context: Context): PendingIntent { val i = Intent(context, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP putExtra(MainActivity.EXTRA_TAB, MainActivity.TAB_FOCUS) } return PendingIntent.getActivity( context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) } private fun serviceAction(context: Context, action: String, requestCode: Int): PendingIntent { val i = Intent(context, TimerService::class.java).setAction(action) return PendingIntent.getService( context, requestCode, i, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) } fun buildOngoing(context: Context): Notification { val running = TimerCore.running val countUp = TimerCore.countUp val taskName = if (TimerCore.taskId > 0) { com.focusbox.app.data.Store.task(TimerCore.taskId)?.title } else null // 没有选任务时给一个中性占位,避免第一行留空白 val headline = taskName?.takeIf { it.isNotBlank() } ?: context.getString(R.string.notif_no_task) val b = NotificationCompat.Builder(context, CHANNEL_TIMER) // 常驻可见的白色秒表图标:透明图标在 EMUI 上会时隐时现,不能保证状态栏一直有提示 .setSmallIcon(R.drawable.ic_notif) .setContentIntent(contentIntent(context)) .setOngoing(true) .setOnlyAlertOnce(true) .setPriority(NotificationCompat.PRIORITY_LOW) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setSilent(true) // 系统模板的"应用名 + 时间"行不需要,时间由自定义布局里的 Chronometer 承担 .setShowWhen(false) // 模板兜底:ROM 若不支持自定义布局,至少还有任务名与读数 .setContentTitle(headline) .setContentText(Dates.clock(TimerCore.displayNow())) val rv = RemoteViews(context.packageName, R.layout.notif_timer) rv.setTextViewText(R.id.tvNotifTask, headline) bindChronometer(rv, running, countUp) rv.setOnClickPendingIntent( R.id.notifPause, serviceAction( context, if (running) TimerService.ACTION_PAUSE else TimerService.ACTION_RESUME, 11, ), ) rv.setImageViewResource( R.id.notifPause, if (running) R.drawable.ic_pause else R.drawable.ic_play, ) rv.setOnClickPendingIntent( R.id.notifStop, serviceAction(context, TimerService.ACTION_STOP, 13), ) b.setCustomContentView(rv) b.setCustomBigContentView(rv) // 模板动作保留作兜底(自定义布局生效时系统不会重复绘制这两颗按钮) b.addAction( NotificationCompat.Action( if (running) R.drawable.ic_pause else R.drawable.ic_play, "", serviceAction( context, if (running) TimerService.ACTION_PAUSE else TimerService.ACTION_RESUME, 21, ), ) ) b.addAction( NotificationCompat.Action( R.drawable.ic_stop, "", serviceAction(context, TimerService.ACTION_STOP, 23), ) ) return b.build() } /** * 把计时读数交给系统 Chronometer。 * * 关键:Chronometer 的时间轴是 SystemClock.elapsedRealtime()(开机后的毫秒数), * 不是 System.currentTimeMillis()(1970 年起的绝对时间)。 * 用后者当 base,两者相差十几亿毫秒,屏幕上就会滚出一长串天文数字。 * * 倒计时:base = 现在(单调钟) + 剩余,配合 countDown 显示"还剩多少"; * 正计时:base = 现在 - 已用,显示"已经过了多久"; * 暂停时 started=false,数字停在刷新那一刻的读数上。 */ private fun bindChronometer(rv: RemoteViews, running: Boolean, countUp: Boolean) { val now = SystemClock.elapsedRealtime() val base: Long val countDown: Boolean if (countUp) { base = now - TimerCore.displayNow() countDown = false } else { // remainingNow() 在运行中是现算、暂停时是快照,两种情况都对得上 base = now + TimerCore.remainingNow() countDown = true } // 方向必须在 base 之前下发:部分 ROM 会按 RemoteViews 指令顺序应用属性, // 先 setChronometer 再切 countDown 会出现先按正计时算、再倒着走的错读数。 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { rv.setChronometerCountDown(R.id.notifChrono, countDown) } rv.setChronometer(R.id.notifChrono, base, null, running) } fun updateOngoing(context: Context) { if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return runCatching { NotificationManagerCompat.from(context).notify(ID_ONGOING, buildOngoing(context)) } } fun showCompletion(context: Context, finishedMode: Int, breakMinutes: Int) { if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return val focusDone = finishedMode == TimerCore.MODE_FOCUS val title = context.getString( if (focusDone) R.string.notif_focus_done else R.string.notif_break_done ) val text = if (focusDone) { context.getString(R.string.notif_focus_done_text, breakMinutes) } else { context.getString(R.string.notif_break_done_text) } val n = NotificationCompat.Builder(context, CHANNEL_ALERT) .setSmallIcon(R.drawable.ic_check) .setContentTitle(title) .setContentText(text) .setContentIntent(contentIntent(context)) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_HIGH) .build() runCatching { NotificationManagerCompat.from(context).notify(ID_ALERT, n) } } fun cancelOngoing(context: Context) { runCatching { NotificationManagerCompat.from(context).cancel(ID_ONGOING) } } }