You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android 14设备中ServiceCompat.startForeground()崩溃问题求助

Android 14前台服务启动崩溃问题(后台视频录制场景)

我正在开发一款Android应用,核心功能是用户退出应用后仍能持续录制视频,通过前台服务实现。已按官方文档要求在Manifest中声明所有必要权限,并且在运行时授予了全部权限,但在Android 14设备上调用ServiceCompat.startForeground()时应用崩溃,抛出以下SecurityException:

java.lang.SecurityException: Starting FGS with type microphone callerApp=ProcessRecord{25db602 15445:com.nerovero.camerago/u0a1030} targetSDK=34 requires permissions: all of the permissions allOf=true [android.permission.FOREGROUND_SERVICE_MICROPHONE] any of the permissions allOf=false [android.permission.CAPTURE_AUDIO_HOTWORD, android.permission.CAPTURE_AUDIO_OUTPUT, android.permission.CAPTURE_MEDIA_OUTPUT, android.permission.CAPTURE_TUNER_AUDIO_INPUT, android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT, android.permission.RECORD_AUDIO] and the app must be in the eligible state/exemptions to access the foreground only permission

以下是相关代码文件:

VideoRecordingService类

import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.camera.core.Camera
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.video.MediaStoreOutputOptions
import androidx.camera.video.Quality
import androidx.camera.video.QualitySelector
import androidx.camera.video.Recorder
import androidx.camera.video.Recording
import androidx.camera.video.VideoCapture
import androidx.camera.video.VideoRecordEvent
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleService
import com.nerovero.camerago.CameraActivity.Companion.vQuality
import java.io.File

class VideoRecordingService : LifecycleService() {
    private val preview = Preview.Builder().build()
    private var cameraSelector = CameraActivity.cameraSelector

    //Initialize the following
    private lateinit var cameraProvider: ProcessCameraProvider
    private lateinit var videoCapture: VideoCapture<Recorder>
    private lateinit var recording: Recording
    private lateinit var camera: Camera

    override fun onCreate() {
        super.onCreate()
        startCameraX()
        // Log.e("logo", "onCreate() from VideoRecordingService is called")
    }

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

        // Log.e("logo", "onStartCommand() from VideoRecordingService is called")
        val audioPermission =
            ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
        val cameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
        if ((audioPermission == PackageManager.PERMISSION_GRANTED) && (cameraPermission == PackageManager.PERMISSION_GRANTED)) {
            //this permission just is just for debugging remove it later on and add it in the intent of calling the
            // foreground service
            Log.e("logo", "the audio & camera permissions are already granted from the CameraActivity")
            //this permission check is subject to removal if I found a solution for the Android 14
            startForegroundService()
        } else {
            Log.e("logo", "the audio & camera permissions are not  granted from the CameraActivity")
        }

        // startRecordingVideo()
        return START_STICKY
    }

    private fun startForegroundService() {
        // Log.e("logo", "startForegroundService() from VideoRecordingService is called")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //try to use resources here
            val channel = NotificationChannel(
                "video_recording_service",
                "Video Recording Service",
                NotificationManager.IMPORTANCE_HIGH
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }

        val notification: Notification = NotificationCompat.Builder(this, "video_recording_service")
            .setContentTitle(getString(R.string.video_recording))
            .setContentText(getString(R.string.video_recording_in_progress))
            .setSmallIcon(R.drawable.recording_on)
            .build()

        ServiceCompat.startForeground(
            this,
            1,
            notification,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // I just added ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
                ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
            } else {
                0
            }
        )

        //Log.e("logo", "the end of startForegroundService()")
        // startForeground(1, notification)
    }

    private fun startRecordingVideo() {
        Log.e("logo", "startRecordingVideo() is called ")
        val name: String = System.currentTimeMillis().toString() + ""
        val fileName = "camerago_$name.mp4"
        val pathValues = ContentValues().apply {
            put(MediaStore.Video.Media.DISPLAY_NAME, fileName)
            put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(
                    MediaStore.Video.Media.RELATIVE_PATH,
                    Environment.DIRECTORY_DCIM + File.separator +
                            getString(R.string.app_name)
                )
            }
        }

        // camera = cameraProvider.bindToLifecycle(this, cameraSelector)
        //initializeCamera()

        val mediaStoreOutputOptions =
            MediaStoreOutputOptions.Builder(contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
                .setContentValues(pathValues).build()

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) !=
            PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return
        }
        recording = videoCapture.output
            .prepareRecording(this, mediaStoreOutputOptions)
            .withAudioEnabled()
            .start(ContextCompat.getMainExecutor(this)) { videoRecordEvent ->
                when (videoRecordEvent) {
                    is VideoRecordEvent.Start -> {
                        Log.e("logo", "VideoRecordEvent.Start from VideoRecordingService")
                    }

                    is VideoRecordEvent.Finalize -> {
                        Log.e("logo", "VideoRecordEvent.Finalize from VideoRecordingService ")
                        cameraProvider.unbind(videoCapture)
                        //I add this code below cause if i don't fdo it the app will crash
                        //saying a recording is already in progress
                        //....................
                        // startCameraX()
                        //.........................................
                    }
                }
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        //this function should be moved to the end of the code
        recording.stop()
    }

    //this is an after code section if it is reliable integrate it to the main code
    //activating the cameraX
    private fun startCameraX() {
        val cameraProviderListenableFuture = ProcessCameraProvider.getInstance(applicationContext) //maybe "this" is better

        cameraProviderListenableFuture.addListener({
            try {
                cameraProvider = cameraProviderListenableFuture.get()
                camera = cameraProvider.bindToLifecycle(this, cameraSelector)
                initializeCamera()
                startRecordingVideo()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }, ContextCompat.getMainExecutor(this))
    }

    //Initialization of the camera
    private fun initializeCamera() {
        try {
            //check the settings
            //initialization of the videoCapture through recorder
            try {
                val recorder =
                    Recorder.Builder().setQualitySelector(QualitySelector.from(vQuality)).build()
                videoCapture = VideoCapture.withOutput(recorder)
            } catch (e: Exception) {
                e.printStackTrace()
                val recorder =
                    Recorder.Builder().setQualitySelector(QualitySelector.from(Quality.HIGHEST))
                        .build()
                videoCapture = VideoCapture.withOutput(recorder)
            }
            cameraProvider.unbindAll()
            cameraProvider.bindToLifecycle(this, cameraSelector, preview, videoCapture)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-feature
        android:name="android.hardware.camera2"
        android:required="false" />
    <uses-feature android:name="android.hardware.camera.any" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--implementation of a file provider in order to be able to share the video to other platforms-->
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.nerovero.camerago.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

        <!--check whether enabled attribute is necessary in the service or not   -->
        <service
            android:name=".VideoRecordingService"
            android:enabled="true"
            android:exported="false"
            android:foregroundServiceType="camera|microphone"
            tools:node="merge" />

        <activity
            android:name=".SettingsActivity"
            android:enabled="true"
            android:exported="false" />

        <activity
            android:name=".PreviewActivity"
            android:exported="true">

        </activity>

        <activity
            android:name=".CameraActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

已尝试修改Manifest中的服务属性,但问题仍未解决。

内容的提问来源于stack exchange,提问作者NeroVero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 04:55:54