Files
FocusBox/src/main/java/com/focusbox/app/service/Notif.kt

211 lines
7.9 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.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)
// 透明小图标:状态栏与通知左侧不再出现应用图标
.setSmallIcon(R.drawable.ic_notif_blank)
.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。
*
* 倒计时:base = 结束时刻,配合 countDown 显示"还剩多少";
* 正计时:base 往前推已用时长,显示"已经过了多久";
* 暂停时 started=false,Chronometer 停在按下暂停那一刻的值。
*/
private fun bindChronometer(rv: RemoteViews, running: Boolean, countUp: Boolean) {
val now = System.currentTimeMillis()
val base: Long
val countDown: Boolean
when {
countUp -> {
base = now - TimerCore.displayNow()
countDown = false
}
running -> {
base = TimerCore.endAtMs()
countDown = true
}
else -> {
base = now + TimerCore.remainingNow()
countDown = true
}
}
rv.setChronometer(R.id.notifChrono, base, null, running)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
rv.setChronometerCountDown(R.id.notifChrono, countDown)
}
}
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) }
}
}