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
85 stars 45 forks source link

[BUG] FlutterBackground is not initialised after letting app run in background #56

Open victor-semenovich-dev opened 2 years ago

victor-semenovich-dev commented 2 years ago

Describe the bug After run the FlutterBackground.initialize() command on the first app start, the application shows the "Let app always run in background?" dialog. If press "Allow", the FlutterBackground.initialize() returns false. FlutterBackground.enableBackgroundExecution() doesn't work after that. The bug is not reproduced on the second app run. In this case the dialog is not shown, and the FlutterBackground.initialize() returns true.

To Reproduce Run the app at the first time and execute the FlutterBackground.initialize().

Expected behavior FlutterBackground.initialize() returns "true" on press "Allow". FlutterBackground.enableBackgroundExecution() also works and returns "true".

Screenshots Screenshot_20220413_101843

Smartphone:

Code

class _HomeRouteState extends State<HomeRoute> {
  @override
  void initState() {
    super.initState();
    const androidConfig = FlutterBackgroundAndroidConfig(
      notificationTitle: 'Интерком',
      notificationText: 'Приложение работает в фоновом режиме',
      notificationImportance: AndroidNotificationImportance.Default,
      notificationIcon: AndroidResource(
        name: 'ic_info_24dp',
        defType: 'drawable',
      ),
      enableWifiLock: true,
    );
    FlutterBackground.initialize(androidConfig: androidConfig)
        .then((value) => debugPrint('FlutterBackground: initialize - $value'));
  }
...
}

[+12805 ms] I/flutter ( 7726): FlutterBackground: initialize - false
flutter doctor -v ``` [✓] Flutter (Channel stable, 2.10.4, on macOS 12.3 21E230 darwin-x64, locale en-BY) • Flutter version 2.10.4 at /Users/victorsemenovich/Development/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision c860cba910 (3 weeks ago), 2022-03-25 00:23:12 -0500 • Engine revision 57d3bac3dd • Dart version 2.16.2 • DevTools version 2.9.2 [✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0) • Android SDK at /Users/victorsemenovich/Library/Android/sdk • Platform android-31, build-tools 31.0.0 • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822) • All Android licenses accepted. [✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome [✓] Android Studio (version 2021.1) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822) [✓] Connected device (2 available) • Pixel 5a (mobile) • 192.168.0.14:41945 • android-arm64 • Android 12 (API 31) • Chrome (web) • chrome • web-javascript • Google Chrome 100.0.4896.88 [✓] HTTP Host Availability • All required HTTP hosts are available • No issues found! ```
Baldur008 commented 2 years ago

Found Solution ?

boldt commented 1 year ago

I can confirm it. On first run, initialize returns false, on second run it returns true.

boldt commented 1 year ago

This workaround works for me:

// Workaround: initialize only works on second run of initialize
// The first initialize ensures, that the permission is set
// The second initialize ensures, that service is set up properly
return await FlutterBackground.initialize(androidConfig: androidConfig).then((value) async {
  // value is false
  if (!value && await FlutterBackground.hasPermissions) {
    await FlutterBackground.initialize(androidConfig: androidConfig).then((value) async {
      // value is true now
      return value;
    });
  }
  return value;
});
janoskranczler commented 1 year ago

The same issue for me on Google Pixel 3A and Samsung Galaxy A13. For me, the workaround doesn't work either. It only works when I restart the app. For the first run, it never works.

luohao123 commented 1 year ago

@janoskranczler how did u resolve it finally?

janoskranczler commented 1 year ago

@janoskranczler how did u resolve it finally?

I couldn't resolve it. It still an issue for me either.

luohao123 commented 1 year ago

@janoskranczler https://pub.dev/packages/background_fetch this lib solves perfectly!

janoskranczler commented 1 year ago

@janoskranczler https://pub.dev/packages/background_fetch this lib solves perfectly!

Thank you! I will take a look.

steveseguin commented 6 months ago

This seemed to work for me, at least wrt to getting it to initialize without an error on first run. Can't speak to how well the background service itself works though. Tested on Android 13 (Pixel 4a) with release and debug builds.

Future<bool> startForegroundService() async {
  final androidConfig = FlutterBackgroundAndroidConfig(
      notificationTitle: '****** background service',
      notificationText: '****** background service',
      notificationImportance: AndroidNotificationImportance.Default,
      notificationIcon: AndroidResource(
        name: 'background_icon',
        defType: 'drawable'
      ),
  );

  try {
      await FlutterBackground.initialize(androidConfig: androidConfig); 
      try {
          await FlutterBackground.enableBackgroundExecution();
      } catch (e) {
      }

      bool initialized = await FlutterBackground.initialize(androidConfig: androidConfig);
      if (initialized) {
          await FlutterBackground.enableBackgroundExecution();
          return true;
      } else {
          print('Error: FlutterBackground not initialized');
          return false;
      }
  } catch (e) {
      print('Error initializing FlutterBackground: $e');
      return false;
  }
}