PAYATHON 2026

Kotlin 在 overlay service 中实现相机,即使 MainActivity 关闭

数据小陈

结论

可以做到,但有两个前提:相机运行在已按 camera 类型启动的 foreground service 中,且 CameraX 绑定到 Service 自己的 LifecycleOwner,不要绑到 MainActivity。如果使用普通 Service,或把 CameraX 绑到 Activity 生命周期,切换到其他应用后 Activity 进入后台或被销毁,CameraX 就会停止,Android 也会禁止后台访问相机。

原因

  • Android 9+ 限制后台应用访问相机。前台服务必须声明正确的 foregroundServiceType;访问相机的服务应使用 camera 类型,Android 14+ 还要声明 FOREGROUND_SERVICE_CAMERA 权限。
  • Service 默认不是 LifecycleOwner。拿 Activity 当 CameraX 的 lifecycle,Activity 一旦不可见,绑定就会失效。
  • 悬浮窗权限 SYSTEM_ALERT_WINDOW 只负责显示 overlay,不会授予后台相机权限。
  • Android 12+/14+ 对从后台临时启动 camera 类型前台服务有限制,最好趁 Activity 仍可见时先把该前台服务启动起来。

实现步骤

  1. 在 Manifest 中声明相机、悬浮窗和前台服务权限,并把 Service 声明为 camera 类型。
  2. Activity 可见时申请 CAMERA 和悬浮窗权限,然后启动前台服务。
  3. Service 继承 LifecycleService,也可以自己实现 LifecycleOwner;CameraX 的 lifecycle 用 Service 本身。
  4. 用 WindowManager 添加包含 PreviewView 和按钮的 overlay。预览建议使用 PreviewView.ImplementationMode.COMPATIBLE,以减少 SurfaceView 在 overlay 中的 z-order 问题。
  5. 拍照用 ImageCapture;在 onDestroy() 中调用 unbindAll() 并移除 overlay。

Manifest 示例:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />

<service
    android:name=".OverlayCameraService"
    android:exported="false"
    android:foregroundServiceType="camera" />

Service 核心代码:

class OverlayCameraService : LifecycleService() {

    private lateinit var windowManager: WindowManager
    private lateinit var root: FrameLayout
    private lateinit var previewView: PreviewView
    private var imageCapture: ImageCapture? = null
    private var cameraProvider: ProcessCameraProvider? = null

    override fun onCreate() {
        super.onCreate()
        windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        startAsForeground()
        showOverlay()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        startCamera()
        return START_STICKY
    }

    private fun startAsForeground() {
        val channelId = "overlay_camera"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(
                NotificationChannel(
                    channelId,
                    "Overlay Camera",
                    NotificationManager.IMPORTANCE_LOW
                )
            )
        }

        val notification = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_camera)
            .setContentTitle("Overlay camera")
            .setContentText("Camera is running")
            .setOngoing(true)
            .build()

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            startForeground(
                1001,
                notification,
                ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA
            )
        } else {
            startForeground(1001, notification)
        }
    }

    private fun showOverlay() {
        if (!Settings.canDrawOverlays(this)) return

        root = FrameLayout(this)
        previewView = PreviewView(this).apply {
            implementationMode = PreviewView.ImplementationMode.COMPATIBLE
        }
        root.addView(
            previewView,
            FrameLayout.LayoutParams(720, 960)
        )

        val captureButton = Button(this).apply {
            text = "拍照"
            setOnClickListener { capturePhoto() }
        }
        root.addView(
            captureButton,
            FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
            ).apply { gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL }
        )

        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            },
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.TOP or Gravity.START
            x = 80
            y = 160
        }
        windowManager.addView(root, params)
    }

    private fun startCamera() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) return

        val future = ProcessCameraProvider.getInstance(this)
        future.addListener({
            cameraProvider = future.get()

            val preview = Preview.Builder().build().also {
                it.setSurfaceProvider(previewView.surfaceProvider)
            }
            imageCapture = ImageCapture.Builder().build()

            try {
                cameraProvider?.unbindAll()
                cameraProvider?.bindToLifecycle(
                    this, // Service 自身作为 LifecycleOwner
                    CameraSelector.DEFAULT_BACK_CAMERA,
                    preview,
                    imageCapture
                )
            } catch (e: Exception) {
                Log.e("OverlayCamera", "bind failed", e)
            }
        }, ContextCompat.getMainExecutor(this))
    }

    private fun capturePhoto() {
        val capture = imageCapture ?: return
        val dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES) ?: filesDir
        val file = File(dir, "overlay_${System.currentTimeMillis()}.jpg")
        val output = ImageCapture.OutputFileOptions.Builder(file).build()

        capture.takePicture(
            output,
            ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onImageSaved(
                    outputFileResults: ImageCapture.OutputFileResults
                ) {
                    Log.d("OverlayCamera", "saved: ${file.absolutePath}")
                }

                override fun onError(exception: ImageCaptureException) {
                    Log.e("OverlayCamera", "capture failed", exception)
                }
            }
        )
    }

    override fun onDestroy() {
        cameraProvider?.unbindAll()
        if (::root.isInitialized) {
            windowManager.removeView(root)
        }
        super.onDestroy()
    }
}

Activity 可见时启动服务:

ContextCompat.startForegroundService(
    this,
    Intent(this, OverlayCameraService::class.java)
)

注意:需要添加 androidx.lifecycle:lifecycle-service 依赖,版本要和项目中的 Lifecycle 保持一致。如果 overlay 使用 ComposeView,还要设置 ViewTreeLifecycleOwner,也可以通过 AndroidView 承载 PreviewView;否则 Compose 在 Service 中可能拿不到正确的 lifecycle 和 saved state owner。

注意事项

  • 不要把 CameraX 绑定到 MainActivity 的 lifecycleScope,也不要用 Activity 作为 lifecycle owner。
  • 趁 Activity 仍可见时启动 camera 类型前台服务,可以避开大部分后台启动前台服务的限制。
  • 用户强制停止应用、撤销相机权限,或者系统/OEM 杀掉 Service 后,overlay 和相机都无法继续运行。普通应用层没有方案能保证这种情况下仍然存活。
  • Android 14+ 要声明 FOREGROUND_SERVICE_CAMERA,并在 startForeground() 中传入 FOREGROUND_SERVICE_TYPE_CAMERA。
  • 预览黑屏时,先检查 overlay 权限、前台服务类型、CameraX 绑定的 lifecycle,再把 PreviewView 改成 COMPATIBLE 或 TextureView。

备注:内容仅供参考。