JulianAssmann / flutter_background

A flutter plugin to keep apps running in the background via foreground services. Android only.
https://pub.dev/packages/flutter_background
MIT License
89 stars 52 forks source link

Initialize fails on first call #76

Open breuerss opened 1 year ago

breuerss commented 1 year ago

Describe the bug The result of

bool initialized = await FlutterBackground.initialize(androidConfig: androidConfig);

is always false, since

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
    try {
        if (alreadyCalled || requestCode != PermissionHandler.PERMISSION_CODE_IGNORE_BATTERY_OPTIMIZATIONS) {
            return false
        }

        alreadyCalled = true

        // THIS IS ALWAYS FALSE
        onSuccess(resultCode == Activity.RESULT_OK)
    } catch (ex: Exception) {
        onError("flutter_background.PermissionHandler", "Error while waiting for user to disable battery optimizations", ex.localizedMessage)
    }

    return true
}

resultCode always contains 0 no matter what the answer.

Even ignoring the return value of initialize in Flutter would not work, since the plugin does not continue to initialize itself.

To Reproduce On the first run with following code:

await FlutterBackground.initialize(androidConfig: androidConfig);

if (await FlutterBackground.hasPermissions) {
  await FlutterBackground.enableBackgroundExecution();
}

Confirm the allow permission request.

The application throws an exception and the background execution is not enabled. The second walk through works, since the permission is then already granted.

Expected behavior

Since the same code works on Android 11 I guess the solution is to find a way to get a proper result code from the permission request. I don't know how to achieve this.

As an alternative for me also works to ignore the result code and always return true.

Smartphone: Observed with:

Seems to work properly on

Thanks for your nice plugin.

JulianAssmann commented 3 months ago

Thanks for creating the issue. Can you please upgrade to the new version of the plugin (1.3.0), update your AndroidManifest.xml according to the new README (specifically including the foreground service types) and report back?