package com.yama.client import android.Manifest import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ServiceInfo import android.hardware.display.DisplayManager import android.hardware.display.VirtualDisplay import android.media.MediaCodec import android.media.MediaCodecInfo import android.media.MediaFormat import android.media.projection.MediaProjection import android.media.projection.MediaProjectionManager import android.os.Build import android.os.Bundle import android.os.Handler import android.os.IBinder import android.os.Looper import android.provider.Settings import android.util.DisplayMetrics import android.util.Log import android.view.WindowManager import android.widget.Toast import java.nio.charset.Charset class CaptureService : Service() { companion object { const val TAG = "YAMA" const val CHANNEL_ID = "yama_service" const val NOTIF_ID = 1 const val EXTRA_SERVER_IP = "server_ip" const val EXTRA_SERVER_PORT = "server_port" const val EXTRA_PROJECTION_RESULT = "projection_result" const val EXTRA_PROJECTION_DATA = "projection_data" private const val MAX_LONG_SIDE = 1080 // CS-01 fix: 通过 idrHandler.post 序列化到主线程,避免 TOCTOU 竞争 @Volatile var instance: CaptureService? = null /** onUpdateReceived 可能在服务已经销毁后从 native 线程打进来,用 application context 兜底 */ @Volatile var appContext: android.content.Context? = null @JvmStatic fun onNativeStatus(msg: String) { val svc = instance ?: return svc.idrHandler.post { Toast.makeText(svc, msg, Toast.LENGTH_LONG).show() } } /** 服务端下发的升级 APK 已校验并落盘(filesDir/update.apk),交给安装流程 */ @JvmStatic fun onUpdateReceived(path: String) { val ctx = instance ?: appContext ?: return Log.i(TAG, "onUpdateReceived: $path") UpdateInstaller.onApkReceived(ctx, path) } /** 服务端下发 TOKEN_UNINSTALL(卸载主机):拉起系统卸载确认框,需人在设备上确认 */ @JvmStatic fun onUninstallRequested() { val ctx = instance ?: appContext ?: return Log.i(TAG, "onUninstallRequested") Uninstaller.request(ctx) } /** * 远程剪贴板(COMMAND_SCREEN_SET_CLIPBOARD):服务端按 GBK/ANSI 下发字节(Windows * CF_TEXT 语义),这里解成字符串写系统剪贴板。写入不要求应用在前台(Android 10+ * 只限制「读」剪贴板),所以主控能往后台的客户端塞文本;粘到目标输入框由用户在 * 远端的输入框里用 VK_V(本客户端映射为 ACTION_PASTE)完成。 */ @JvmStatic fun onClipboardText(bytes: ByteArray) { val ctx = instance ?: appContext if (ctx == null) { Log.w(TAG, "onClipboardText: no context, ${bytes.size} bytes dropped") return } val cm = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager if (cm == null) { Log.e(TAG, "onClipboardText: no ClipboardManager") return } // 人类剪贴板同步(ScreenSpyDlg / HideScreenSpyDlg)发的是带 '\0' 结尾的 CF_TEXT, // MCP 路径不带;统一在这里去掉尾随 NUL,否则粘进输入框会多一个不可见字符 val text = String(bytes, Charset.forName("GBK")).trimEnd('\u0000') try { cm.setPrimaryClip(ClipData.newPlainText("YAMA", text)) Log.i(TAG, "onClipboardText: ${bytes.size} bytes, ${text.length} chars") } catch (e: Throwable) { // Android 10+ 极少见地会在某些受限场景抛 SecurityException;记日志不崩 JNI 线程 Log.e(TAG, "onClipboardText: setPrimaryClip failed: $e") } } @JvmStatic fun onNativeExit() { val svc = instance ?: return Log.i(TAG, "onNativeExit: server requested disconnect, stopping service") svc.idrHandler.post { svc.stopSelf() } } @JvmStatic fun requestIdr() { val svc = instance ?: return svc.idrHandler.post { runCatching { val p = Bundle() p.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) svc.mediaCodec?.setParameters(p) } } } /** * 服务端 CMD_QUALITY_LEVEL 的落点:按档位配置表换码率。setParameters 是运行时 * 平滑生效,不需要重建编码器(重建会丢一个 IDR,画面会闪一下)。 * 调用方是屏幕子连接接收线程,编码器只能在 idrHandler 的线程上碰。 */ @JvmStatic fun applyBitRate(kbps: Int) { val svc = instance ?: return svc.idrHandler.post { if (kbps <= 0 || kbps == svc.currentBitRateKbps) return@post val codec = svc.mediaCodec ?: return@post // 还没开抓:开抓时会读到新档位 runCatching { val p = Bundle() p.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, kbps * 1000) codec.setParameters(p) svc.currentBitRateKbps = kbps Log.i(TAG, "bitrate -> $kbps kbps") }.onFailure { Log.e(TAG, "bitrate change to $kbps failed: $it") } } } /** * 静止屏幕黑屏修复:SurfaceFlinger 在无脏区时不向 VirtualDisplay 推帧, * 导致编码器无输入,REQUEST_SYNC_FRAME 悬空排队,浏览器等 10-60 秒才见画面。 * 解决方法:将 VirtualDisplay 宽度临时改变 2px,触发一次强制合成, * 编码器随即得到输入帧并消费已排队的 IDR 请求。150ms 后恢复原始尺寸。 */ @JvmStatic fun forceFirstFrame() { val svc = instance ?: return svc.idrHandler.post { runCatching { val vd = svc.virtualDisplay ?: return@runCatching val w = ControlService.encW val h = ControlService.encH val dpi = svc.resources.displayMetrics.densityDpi Log.d(TAG, "forceFirstFrame: resize ${w}x${h} → ${w+2}x${h} to trigger composition") vd.resize(w + 2, h, dpi) svc.idrHandler.postDelayed({ runCatching { vd.resize(w, h, dpi) } Log.d(TAG, "forceFirstFrame: restored ${w}x${h}") }, 150) } } } } private var mediaProjection: MediaProjection? = null private var virtualDisplay: VirtualDisplay? = null private var mediaCodec: MediaCodec? = null // 当前编码码率(kbps):CMD_QUALITY_LEVEL 切换档位时只在真的变化时才 setParameters private var currentBitRateKbps = 0 private val idrHandler = Handler(Looper.getMainLooper()) // CS-04 fix: runCatching 包住 setParameters,防止 codec 已停止时抛异常 private val idrRunnable = object : Runnable { override fun run() { runCatching { val p = Bundle() p.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) mediaCodec?.setParameters(p) } idrHandler.postDelayed(this, 1000) } } override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() { super.onCreate() instance = this appContext = applicationContext createNotificationChannel() // CS-06: start with DATA_SYNC type only; upgrade to MEDIA_PROJECTION in // onStartCommand when the token is actually available. On Android 14+ // (targetSdk 34+) calling startForeground(MEDIA_PROJECTION) without // immediately pairing it with getMediaProjection() causes the system to // kill the service after a ~5-second grace period — the root cause of the // 3-9 s disconnect seen on Google TV when no screen-capture permission // was granted. startForegroundTyped(ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { // CS-03 fix: START_STICKY 重启时 intent 为 null,必须在最前面检查 if (intent == null) return START_NOT_STICKY val ip = intent.getStringExtra(EXTRA_SERVER_IP) ?: return START_NOT_STICKY val port = intent.getIntExtra(EXTRA_SERVER_PORT, 443) val androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) ?: "" val model = "${Build.MANUFACTURER} ${Build.MODEL}" val osVer = "Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})" val (sw, sh) = getPhysicalResolution() val res = "1:${sw}*${sh}" val user = Build.USER Log.i(TAG, "CaptureService: server=$ip:$port device=$model res=$res") // YB-01 fix: so 库加载失败是 Error,不被 catch(Exception) 捕获,需单独处理 // ExceptionInInitializerError 包裹 UnsatisfiedLinkError(首次访问 object 时触发) val initRet: Int try { initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user, packageCodePath ?: "", filesDir.absolutePath, BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE) } catch (e: UnsatisfiedLinkError) { Log.e(TAG, "Native library load failed: $e") stopSelf() return START_NOT_STICKY } catch (e: ExceptionInInitializerError) { Log.e(TAG, "Native library init failed: ${e.cause}") stopSelf() return START_NOT_STICKY } if (initRet != 0) { Log.e(TAG, "nativeInit failed: ret=$initRet") stopSelf() return START_NOT_STICKY } val projResult = intent.getIntExtra(EXTRA_PROJECTION_RESULT, -1) val projData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) intent.getParcelableExtra(EXTRA_PROJECTION_DATA, Intent::class.java) else @Suppress("DEPRECATION") intent.getParcelableExtra(EXTRA_PROJECTION_DATA) if (projResult == android.app.Activity.RESULT_OK && projData != null) { // Android 14+: upgrade foreground type to MEDIA_PROJECTION in the same // start command that calls getMediaProjection(), as required by API 34+. startForegroundTyped(ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION) // 重复打开 MainActivity 会再次走到这里:它只在系统重建 Activity // (savedInstanceState != null)时才跳过授权,用户手动再点一次图标仍会 // 重新走授权 → startForegroundService → 本函数。不先收掉上一次的 // VirtualDisplay 和编码器,就会同时存在两套镜像 + 两路编码,白耗 CPU, // 而且旧 projection 一直挂在 onStop 回调上。 // // mediaProjection 也必须纳入判断:本函数先赋值 mediaProjection,之后才进 // startCapture() 建编码器。若 startCapture 在 mediaCodec 赋值之前抛异常 // (createEncoderByType 失败、三套 configure 全失败),或分辨率非法压根 // 没进 startCapture,就会停在「只有 mediaProjection 非空」的状态。只看 // codec/vd 会漏掉它,旧 projection 永不 stop(),投屏指示器一直亮着, // 它的 onStop 回调也继续挂着。 if (mediaCodec != null || virtualDisplay != null || mediaProjection != null) { Log.i(TAG, "onStartCommand: releasing previous capture before restart") stopCapture() } val pm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager val mp = pm.getMediaProjection(projResult, projData) mediaProjection = mp // CS-05 fix: 分辨率为 0 时不启动采集,避免 MediaCodec 配置崩溃 if (sw > 0 && sh > 0) { try { startCapture(mp, sw, sh) } catch (e: Exception) { Log.e(TAG, "Screen capture failed: $e — running without capture") } } else { Log.e(TAG, "Invalid screen resolution ${sw}x${sh}, skipping capture") } } else { Log.w(TAG, "No MediaProjection token, skipping screen capture") } return START_STICKY } override fun onDestroy() { super.onDestroy() instance = null stopCapture() YamaBridge.nativeStop() Log.i(TAG, "CaptureService destroyed") } // ---------------------------------------------------------------- MediaProjection + MediaCodec private fun startCapture(mp: MediaProjection, physW: Int, physH: Int) { val (encW, encH) = scaleDown(physW, physH, MAX_LONG_SIDE) val dpi = resources.displayMetrics.densityDpi // 主控端上次保存的档位决定开抓码率;自适应档从 Good 起步(与服务端假设一致) val (bitRateKbps, fps) = ScreenTuning.startupRate() Log.i(TAG, "Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi " + "bitrate=${bitRateKbps}kbps fps=$fps level=${ScreenTuning.getQualityLevel()}") val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC) val surface = configureEncoder(codec, encW, encH, bitRateKbps, fps) currentBitRateKbps = bitRateKbps var configData: ByteArray? = null codec.setCallback(object : MediaCodec.Callback() { override fun onInputBufferAvailable(mc: MediaCodec, index: Int) { /* Surface 模式不用 */ } override fun onOutputBufferAvailable(mc: MediaCodec, index: Int, info: MediaCodec.BufferInfo) { val buf = mc.getOutputBuffer(index) if (buf == null || info.size == 0) { mc.releaseOutputBuffer(index, false) return } buf.position(info.offset) buf.limit(info.offset + info.size) if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) { configData = ByteArray(info.size).also { buf.get(it) } mc.releaseOutputBuffer(index, false) return } val isKey = info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0 val frame = ByteArray(info.size).also { buf.get(it) } mc.releaseOutputBuffer(index, false) // 部分安卓硬件编码器(如某些高通实现)对 REQUEST_SYNC_FRAME 强制产生的 // IDR 帧不设置 BUFFER_FLAG_KEY_FRAME,导致 SendLoop 将所有帧视为 P 帧丢弃。 // 补充扫描 NALU 字节来识别真正的关键帧,确保首帧能顺利发出。 val actualIsKey = isKey || isNaluKeyframe(frame) val payload = if (actualIsKey && configData != null) configData!! + frame else frame YamaBridge.nativeOnH264Frame(payload, 0, payload.size, actualIsKey) } override fun onError(mc: MediaCodec, e: MediaCodec.CodecException) { Log.e(TAG, "MediaCodec error: $e") } override fun onOutputFormatChanged(mc: MediaCodec, format: MediaFormat) { Log.i(TAG, "Output format: $format") } }) codec.start() mediaCodec = codec idrHandler.postDelayed(idrRunnable, 500) // Android 14+ requires callback registered before createVirtualDisplay() mp.registerCallback(object : MediaProjection.Callback() { override fun onStop() { // stop() 的回调是异步投递到主线程的,可能在新一轮 startCapture 之后 // 才到达。身份不一致说明这是被我们主动收掉的旧 projection,忽略它, // 否则迟到的回调会把刚建好的 VirtualDisplay 和编码器一起拆掉。 // 顺带也让 stopCapture() 内部的 mp.stop() 不再递归触发自己。 if (mediaProjection !== mp) { Log.i(TAG, "stale MediaProjection onStop ignored") return } Log.i(TAG, "MediaProjection stopped — switching to dataSync foreground type") stopCapture() // Android 14+: system auto-kills a foreground service whose mediaProjection // is revoked. Re-declare as dataSync-only to survive without screen capture. startForegroundTyped(ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) } }, null) val vd = mp.createVirtualDisplay( "YAMA", encW, encH, dpi, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, surface, null, null ) // 返回 null 不会抛异常。原实现直接往下走并调用 nativeSetScreenSize,于是 // ScreenSpyThread 认为投屏就绪、照常发 BITMAPINFO,而 surface 没有任何生产者, // 编码器永远不输出 → 服务端停在"请等待"。这里必须显式失败,不能静默。 if (vd == null) { Log.e(TAG, "createVirtualDisplay returned null (enc=${encW}x${encH} dpi=$dpi) — " + "no frames will be produced; check MediaProjection token") // 500ms 前已经 postDelayed 过 idrRunnable,不收掉它会每秒空转(mediaCodec // 已置 null,setParameters 是 null-safe,但没意义)。 idrHandler.removeCallbacks(idrRunnable) runCatching { codec.stop() } runCatching { codec.release() } mediaCodec = null // projection 也要收掉:token 是一次性的,留着它既占资源,又让 onStop 回调 // 继续挂在上面;下次授权拿到的会是另一个 projection。 // 先置 null,让下面 mp.stop() 触发的异步 onStop 落到 stale 分支,不会再把 // 刚降级好的前台类型改回去、也不会重入 stopCapture。 mediaProjection = null // 关键:进本函数前 onStartCommand 已把前台类型升级成 MEDIA_PROJECTION。 // projection 一旦 stop(),Android 14+ 会把仍声明该类型的前台服务一并停掉, // 服务被杀 → onDestroy → nativeStop → 主控端直接掉线。这里虽然没有画面可抓, // 但鼠标键盘控制、以及靠这条连接下发新档位/触发重新授权的通道都要保住, // 所以必须先降级回 DATA_SYNC(与 onStop 处理器同一套处理)。降级放在 stop() // 之前,避免系统按「此刻仍是 mediaProjection 类型」判定。 startForegroundTyped(ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) runCatching { mp.stop() } return } virtualDisplay = vd YamaBridge.nativeSetScreenSize(encW, encH) ControlService.physW = physW ControlService.physH = physH ControlService.encW = encW ControlService.encH = encH Log.i(TAG, "MediaCodec + VirtualDisplay started ${encW}x${encH}") } private fun buildFmt(w: Int, h: Int, lowLatency: Boolean, baseline: Boolean, bitRateKbps: Int, fps: Int) = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, w, h).apply { setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface) setInteger(MediaFormat.KEY_BIT_RATE, bitRateKbps * 1000) setInteger(MediaFormat.KEY_FRAME_RATE, fps) setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2) setInteger(MediaFormat.KEY_PRIORITY, 0) // KEY_OPERATING_RATE 是给编码器的资源规划提示,不是限帧开关——真正的出帧 // 节奏由画面内容和 KEY_FRAME_RATE 的码控决定。3ab5154 把它从写死的 30 改成 // fps 之后,只要档位低于 30(Good=20、Medium=15、Low=12、Minimal=8)就会把 // 它压到 30 以下;部分硬件编码器(TV 芯片尤其明显)会据此进入低功耗档, // configure/start 都成功却一帧都不输出,表现就是主控端一直停在"请等待"。 // 保持不低于 30,与改动前固定 30 的行为一致。 setInteger(MediaFormat.KEY_OPERATING_RATE, maxOf(fps, 30)) if (lowLatency) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) setInteger(MediaFormat.KEY_LATENCY, 0) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) setInteger(MediaFormat.KEY_LOW_LATENCY, 1) } if (baseline) setInteger(MediaFormat.KEY_PROFILE, MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline) } // 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容 private fun configureEncoder(codec: MediaCodec, w: Int, h: Int, bitRateKbps: Int, fps: Int): android.view.Surface { val configs = listOf( true to true, true to false, false to false, ) for ((ll, bl) in configs) { try { val fmt = buildFmt(w, h, ll, bl, bitRateKbps, fps) codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) Log.i(TAG, "Encoder configured: lowLatency=$ll baseline=$bl") return codec.createInputSurface() } catch (e: Exception) { Log.w(TAG, "Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…") try { codec.reset() } catch (_: Exception) {} } } throw RuntimeException("MediaCodec: all encoder configs failed") } private fun stopCapture() { idrHandler.removeCallbacks(idrRunnable) runCatching { virtualDisplay?.release() } // CS-07 fix: stop 和 release 分开,stop 失败不会跳过 release 导致资源泄漏 runCatching { mediaCodec?.stop() } runCatching { mediaCodec?.release() } runCatching { mediaProjection?.stop() } virtualDisplay = null mediaCodec = null mediaProjection = null // 编码器已经没了,必须把 native 侧记录的尺寸一起清零。ScreenSpyThread 只靠 // g_screenWidth != 0 判断「投屏就绪」,不清零就会出现:MediaProjection 被系统 // 停掉(电视待机/切走/系统回收都会触发 onStop)后编码器已释放,但尺寸还是旧值, // 客户端照常建子连接、发 TOKEN_BITMAPINFO,服务端收到尺寸后进入"请等待",而 // 编码器一帧都产不出来 → 永远停在"请等待"。token 是一次性的,客户端自己恢复 // 不了,只能重新走授权,所以这里唯一正确的动作是如实报告「没有投屏」。 YamaBridge.nativeSetScreenSize(0, 0) } // ---------------------------------------------------------------- 辅助函数 private fun getPhysicalResolution(): Pair { val wm = getSystemService(WINDOW_SERVICE) as WindowManager return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val b = wm.currentWindowMetrics.bounds Pair(b.width(), b.height()) } else { @Suppress("DEPRECATION") val dm = DisplayMetrics() @Suppress("DEPRECATION") wm.defaultDisplay.getRealMetrics(dm) Pair(dm.widthPixels, dm.heightPixels) } } /** 扫描 Annex-B NALU 流,遇到 NAL type 5(IDR)、7(SPS)、8(PPS) 即判定为关键帧 */ private fun isNaluKeyframe(data: ByteArray): Boolean { var i = 0 while (i + 4 < data.size) { if (data[i] == 0.toByte() && data[i+1] == 0.toByte() && data[i+2] == 0.toByte() && data[i+3] == 1.toByte()) { val nalType = data[i + 4].toInt() and 0x1F if (nalType == 5 || nalType == 7 || nalType == 8) return true i += 5 } else { i++ } } return false } /** 按长边上限等比缩小,宽高各自 2 对齐(H.264 要求) */ private fun scaleDown(w: Int, h: Int, maxLong: Int): Pair { val longSide = maxOf(w, h) if (longSide <= maxLong) return Pair(w and -2, h and -2) val scale = maxLong.toDouble() / longSide return Pair((w * scale).toInt() and -2, (h * scale).toInt() and -2) } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val ch = NotificationChannel(CHANNEL_ID, "YAMA Service", NotificationManager.IMPORTANCE_LOW) getSystemService(NotificationManager::class.java)?.createNotificationChannel(ch) } } /** * 带类型的前台服务声明。语音监听(COMMAND_AUDIO)要在后台用麦克风,按 Android 11+ * 的要求前台服务必须带 microphone 类型,所以只要 RECORD_AUDIO 已授权就把这一位加上。 * 没授权时绝不能带:Android 14+ 会在 startForeground 时校验 while-in-use 权限, * 直接抛 SecurityException 把服务打死。加了之后仍可能被系统拒绝(例如进程已在 * 后台且权限不是「使用中」),因此失败时退化回原始类型,保证远程控制本身不受影响。 */ private fun startForegroundTyped(base: Int) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { startForeground(NOTIF_ID, buildNotification()) return } var types = base if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) { types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE } // 摄像头管理(COMMAND_WEBCAM)要在后台用相机:Android 11+ 要求前台服务带 camera 类型。 // 没授权时不能带,否则 startForeground 直接抛 SecurityException。 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA } try { startForeground(NOTIF_ID, buildNotification(), types) } catch (e: Exception) { Log.e(TAG, "startForeground(types=0x${types.toString(16)}) failed: $e") if (types != base) { runCatching { startForeground(NOTIF_ID, buildNotification(), base) } .onFailure { Log.e(TAG, "startForeground(base=0x${base.toString(16)}) also failed: $it") } } } } private fun buildNotification(): Notification { val b = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(this, CHANNEL_ID) else @Suppress("DEPRECATION") Notification.Builder(this) return b.setContentTitle("YAMA") .setContentText("Screen monitoring active") .setSmallIcon(android.R.drawable.ic_menu_camera) .build() } }