[JetpackCompose Android] Crashing when starting foreground service over API level 34

Android

Background

When I start the integration test in my app, it crached when starting foreground service.

fun onCreate() {
    //... Some product codes
    Intent(this, ForegroundService::class.java).also {
            ContextCompat.startForegroundService(this, it) // crash
        }
    // ...
}

It says

Caused by: java.lang.SecurityException: .....

What does it mean?

Cause of problem

From Android14 we have to ask the detail of why you use foreground service in your application.

Foreground service types  |  Background work  |  Android Developers

For example, If you want to stay keeping camera up when app goes back ground

you need to add not only FOREGROUND_SERVICE but also FOREGROUND_SERVICE_CAMERA in AndroidManifest.xml.

Finally my AndroidManifest.xml is like the below.

<?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-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />

    <application
            <service
            android:name=".ForegroundService"
            android:foregroundServiceType="dataSync"/>
        // your configurations
    </application>

</manifest>

It extracts the most important parts in AndroidManifext.xml. In my case, I use FOREGROUND_SERVICE_DATA_SYNC so I added user-permission about Foreground Service and service in application.

Then in your product code, you must start Foreground Service after get granted properly permissions.

For example, I wanted to get read and write external storage permisssions especially media. After confirming granted properly permissions you ca launch foreground service like the below.

private fun onGrantedPermission() {
// Background executing
    Intent(this, ForegroundService::class.java).also {
        ContextCompat.startForegroundService(this, it)
}
}

This is what I avoid crashing app when starting Foreground Service.

コメント

タイトルとURLをコピーしました