Dev-hwang / flutter_foreground_task

This plugin is used to implement a foreground service on the Android platform.
https://pub.dev/packages/flutter_foreground_task
MIT License
140 stars 105 forks source link

Suggestion: Handling Exceptions for Foreground Services on Certain Android Versions #237

Closed WingCH closed 1 month ago

WingCH commented 1 month ago

We are encountering an issue where various foreground services, such as startForegroundService, fail for unknown reasons on some Android versions. This issue seems to be related to the restrictions mentioned in the official Android documentation: Background work restrictions.

Specifically, we are encountering the ForegroundServiceStartNotAllowedException. If this exception is thrown, it would make debugging easier.

Here is an example code snippet demonstrating the issue:

// android/src/main/kotlin/com/pravera/flutter_foreground_task/service/ForegroundServiceManager.kt

fun start(context: Context, arguments: Any?): Boolean {
    try {
        val nIntent = Intent(context, ForegroundService::class.java)
        val argsMap = arguments as? Map<*, *>
        ForegroundServiceStatus.setData(context, ForegroundServiceAction.START)
        NotificationOptions.setData(context, argsMap)
        ForegroundTaskOptions.setData(context, argsMap)
        ForegroundTaskData.setData(context, argsMap)
        NotificationContent.setData(context, argsMap)
        ContextCompat.startForegroundService(context, nIntent)
    } catch (e: Exception) {
        throw e // Added to facilitate debugging
    }

    return true
}
Dev-hwang commented 1 month ago

https://github.com/Dev-hwang/flutter_foreground_task/tree/feat-%23237

I added the code so that the developer can handle the service request error. will publish atfer testing

WingCH commented 1 month ago

Good! Thanks for your quick follow-up.

Dev-hwang commented 1 month ago

Please update to the latest version and check.