From 8d7d89f2f32057539a8d5f31b4b0c7eea47fb900 Mon Sep 17 00:00:00 2001 From: Jorge Pabon Date: Wed, 25 Jan 2023 11:43:55 +0700 Subject: [PATCH] Fixed: android background fails on first run On latest versions of Android initialization fails on first run. If this happens, after getting the permissions, we re-try the initialization. Also: - The notification is not longer used by default. - Badge removed from the icon when the notification is used. Close #162 --- .../platform_background_manager_mobile.dart | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/app/utils/platform/platform_background_manager_mobile.dart b/lib/app/utils/platform/platform_background_manager_mobile.dart index 94306a2c0..0d332d2e4 100644 --- a/lib/app/utils/platform/platform_background_manager_mobile.dart +++ b/lib/app/utils/platform/platform_background_manager_mobile.dart @@ -15,6 +15,7 @@ class PlatformBackgroundManagerMobile notificationText: S.current.messageBackgroundNotificationAndroid, notificationIcon: const AndroidResource(name: 'notification_icon'), notificationImportance: AndroidNotificationImportance.Default, + showBadge: false, enableWifiLock: true, ); @@ -36,9 +37,25 @@ class PlatformBackgroundManagerMobile }); } - hasPermissions = await FlutterBackground.initialize(androidConfig: config); + // On recent Android versions (13), the first time the plugin is initialized, + // it fails -even after the user granted permissions. Then on the second run + // it works as expected. + // + // There is curently an issue referencing this in the plugin's repository, + // and the workaround for it: + // https://github.com/JulianAssmann/flutter_background/issues/56#issuecomment-1218307725 + final initializationOk = + await FlutterBackground.initialize(androidConfig: config) + .then((initialized) async { + final permissionsOk = await FlutterBackground.hasPermissions; + if (!initialized && permissionsOk) { + return await FlutterBackground.initialize(androidConfig: config); + } + + return initialized; + }); - if (hasPermissions) { + if (initializationOk) { final backgroundExecution = await FlutterBackground.enableBackgroundExecution();