package com.focusbox.app.service import android.content.Context import android.content.res.Configuration import android.graphics.PixelFormat import android.os.Build import android.provider.Settings import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.WindowManager import android.widget.TextView import com.focusbox.app.R import com.focusbox.app.data.Store import com.focusbox.app.util.Dates import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale /** * 锁屏悬浮窗:计时中锁屏/灭屏时,把黑底倒计时窗口直接画在锁屏之上。 * * 为什么用悬浮窗:鸿蒙 4.0 对「后台弹出界面」的限制只拦 startActivity * (实测开了权限也拦,全屏意图灭屏投递也不可靠),而 WindowManager.addView * 悬浮窗不属于 Activity 启动,只要用户授了「悬浮窗」权限就能稳定盖在锁屏上 * ——这正是专注清单等 App 锁屏显示的做法。 * * 窗口内容直接复用锁屏页布局(activity_lock_screen),inflate 时系统按当前 * 横竖屏自动选 layout 或 layout-land,旋转后重建窗口即可切换排版。 * FLAG_NOT_FOCUSABLE 不抢按键(不影响锁屏密码输入),点击任意处关闭。 */ object LockOverlay { private var root: View? = null private var wm: WindowManager? = null private var orientation = Configuration.ORIENTATION_PORTRAIT private val clockFmt = SimpleDateFormat("HH:mm", Locale.getDefault()) /** 悬浮窗窗口是否正显示在锁屏上 */ fun isShowing(): Boolean = root != null /** 用户是否已授予「悬浮窗」权限 */ fun canShow(context: Context): Boolean = Settings.canDrawOverlays(context) /** 显示(幂等):已在显示或无权限时不重复添加 */ fun show(context: Context) { if (root != null || !canShow(context)) return val ctx = context.applicationContext val manager = ctx.getSystemService(Context.WINDOW_SERVICE) as WindowManager var view: View? = null var added = false try { val v = LayoutInflater.from(ctx).inflate(R.layout.activity_lock_screen, null) view = v v.setOnClickListener { hide() } // API 26+ 用应用悬浮窗类型;更旧版本退回 TYPE_PHONE(本应用 minSdk 24) val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY } else { @Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE } // 关键:EMUI 把悬浮窗限制在状态栏以下的内容区里(顶部时间/信号/电池露出来)。 // 对策是把窗口做得比屏幕更大并向上顶出——高度补上状态栏和导航栏, // y 偏移取负的状态栏高度,配 FLAG_LAYOUT_NO_LIMITS 允许越界绘制, // 黑底就完整盖住状态栏区域(护眼滤镜类 App 同款做法) val res = ctx.resources val sbId = res.getIdentifier("status_bar_height", "dimen", "android") val navId = res.getIdentifier("navigation_bar_height", "dimen", "android") val statusBar = if (sbId > 0) res.getDimensionPixelSize(sbId) else 0 val navBar = if (navId > 0) res.getDimensionPixelSize(navId) else 0 val lp = WindowManager.LayoutParams( res.displayMetrics.widthPixels, res.displayMetrics.heightPixels + statusBar + navBar, type, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, PixelFormat.TRANSLUCENT, ) lp.gravity = Gravity.TOP lp.x = 0 lp.y = -statusBar manager.addView(v, lp) added = true root = v wm = manager orientation = ctx.resources.configuration.orientation render(v) } catch (_: Exception) { // addView 成功之后再抛异常(例如 render 里找控件)时,窗口已经挂在屏幕上了。 // 之前只把 root 置空,窗口却留着 → isShowing() 返回 false,谁也关不掉它, // 用户只能重启手机。这里必须先把窗口摘掉再清状态。 val v = view if (added && v != null) runCatching { manager.removeView(v) } root = null wm = null } } /** 关闭(幂等):窗口不存在时无事发生 */ fun hide() { val view = root ?: return root = null wm?.let { runCatching { it.removeView(view) } } wm = null } /** * 每秒刷新读数;顺带做两件保活级检查: * 1. 用户已解锁(keyguard 解除)→ 自动关窗——不依赖 USER_PRESENT 广播, * 广播在个别 ROM 上时序不稳,靠这秒级兜底保证解锁后不留全屏黑窗挡桌面; * 2. 横竖屏变化 → 重建窗口换对应排版(悬浮窗不经过 Activity 重建)。 */ fun update(context: Context) { val view = root ?: return val km = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager if (!km.isKeyguardLocked()) { hide() return } val current = context.resources.configuration.orientation if (current != orientation) { hide() show(context) return } render(view) } private fun render(view: View) { val now = TimerCore.displayNow() // 计时结束:窗口使命完成,自动关闭 if (!TimerCore.running && now <= 0) { hide() return } val cal = Calendar.getInstance() view.findViewById(R.id.tvLockDate)?.text = "${Dates.mdLong(cal.timeInMillis)} 星期${Dates.weekdayShort(weekdayIndex(cal))}" view.findViewById(R.id.tvLockClock)?.text = clockFmt.format(cal.time) view.findViewById(R.id.tvLockCountdown)?.text = Dates.clock(now) val task = if (TimerCore.taskId > 0) Store.task(TimerCore.taskId)?.title else null view.findViewById(R.id.tvLockTask)?.text = task?.takeIf { it.isNotBlank() } ?: view.context.getString(R.string.notif_no_task) } /** Calendar 的 DAY_OF_WEEK(周日=1)转成 weekdayShort 的下标(周一=0 … 周日=6) */ private fun weekdayIndex(cal: Calendar): Int = (cal.get(Calendar.DAY_OF_WEEK) + 5) % 7 }