I had problems with starting foreground service on Android 14 and got the following problem:
Caused by: java.lang.SecurityException: Starting FGS with type mediaProjection callerApp=ProcessRecord{bb90f1f 12974:com.xxxxxxx} targetSDK=34 requires permissions: all of the permissions allOf=true [android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION] any of the permissions allOf=false [android.permission.CAPTURE_VIDEO_OUTPUT, android:project_media]
Below is how I declare it in the Manifest file:
<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_MEDIA_PROJECTION"
tools:ignore="SystemPermissionTypo" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE"
tools:ignore="SystemPermissionTypo" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA"
tools:ignore="SystemPermissionTypo" />
....
<service
android:name=".service.MyService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="mediaProjection|camera|microphone"
/>
Even though the following runtime permissions have been requested:
...
requestForegroundPermission.launch(
arrayOf(
Manifest.permission.POST_NOTIFICATIONS,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA,
)
)
....
After the above permissions are granted I call “manager.createScreenCaptureIntent()”:
.....
val manager: MediaProjectionManager =
getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
startScreenCaptureForResult.launch(manager.createScreenCaptureIntent())
.....
private val startScreenCaptureForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK && result.data != null) {
val intent = Intent(this, MyService::class.java)
intent.putExtra(RESULT_DATA_SCREEN_RECORDER, data)
startForegroundService(intent)
}
}
And below is the code in my Service:
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
....
startForeground(
NOTIFICATION_ID,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION or
ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA or
ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
)
...
resultCode = intent.getIntExtra(RESULT_CODE_SCREEN_RECORDER, -1)
resultData = intent?.getParcelableExtra(RESULT_DATA_SCREEN_RECORDER,Intent::class.java)!!
val mediaProjection = (getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager).getMediaProjection(resultCode, resultData)
....
}
New contributor
Victor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.