Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

flutterLocalNotificationsPlugin.initialize block app open in release mode #2391

Closed
cruvie opened this issue Aug 20, 2024 · 14 comments
Closed

Comments

@cruvie
Copy link

cruvie commented Aug 20, 2024

Describe the bug
flutterLocalNotificationsPlugin.initialize block app open in release mode, but works fine in debug

To Reproduce
git clone https://github.com/cruvie/demo
flutter build apk
install build/app/outputs/flutter-apk/app-release.apk on any android platform
the app is blocked and cannot enter home page

Expected behavior
after installing can open the app with no blocking

Sample code to reproduce the problem
main.dart

import 'package:flutter/material.dart';

import 'local_notification.dart';

Future<void> main() async {

  WidgetsFlutterBinding.ensureInitialized();

  await MgrLocalNotification.init();

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

local_notification.dart

import 'dart:io';

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class MgrLocalNotification {
  static final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  /// 初始化消息通知器
  static init() async {
    // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
    ///安卓
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('app_icon');

    ///iOS/MacOS 请求权限,也可以滞后请求
    final DarwinInitializationSettings initializationSettingsDarwin =
        DarwinInitializationSettings(
      requestSoundPermission: false,
      requestBadgePermission: false,
      requestAlertPermission: false,
      onDidReceiveLocalNotification:
          (int id, String? title, String? body, String? payload) async {
        print('onDidReceiveLocalNotification');
      },
    );

    ///Linux
    final LinuxInitializationSettings initializationSettingsLinux =
        LinuxInitializationSettings(
            defaultActionName: 'Open notification',
            defaultIcon: AssetsLinuxIcon('icons/app_icon.png'));

    ///初始化
    final InitializationSettings initializationSettings =
        InitializationSettings(
            android: initializationSettingsAndroid,
            iOS: initializationSettingsDarwin,
            macOS: initializationSettingsDarwin,
            linux: initializationSettingsLinux);
    ///comment this can fix blocking
    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onDidReceiveNotificationResponse:
            ToolLocalNotification.onDidReceiveNotificationResponse);

    ///请求权限 android
    if (Platform.isAndroid) {
      final AndroidFlutterLocalNotificationsPlugin? androidImplementation =
          flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
              AndroidFlutterLocalNotificationsPlugin>();

      await androidImplementation?.requestNotificationsPermission();
    }

    ///请求权限 ios/macos
    if (Platform.isIOS || Platform.isMacOS) {
      await flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              IOSFlutterLocalNotificationsPlugin>()
          ?.requestPermissions(
            alert: true,
            badge: true,
            sound: true,
          );
      await flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              MacOSFlutterLocalNotificationsPlugin>()
          ?.requestPermissions(
            alert: true,
            badge: true,
            sound: true,
          );
    }

    ///请求权限 linux
    if (Platform.isLinux) {
      flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
          LinuxFlutterLocalNotificationsPlugin>();
    }
  }
}

class ToolLocalNotification {
  static plainNotification(int id, String title, String msg) async {
    //在这里,第一个参数是通知的 id,对于所有会导致显示通知的方法都是通用的。
    // 这通常为每个通知设置一个唯一的值,因为多次使用相同的 id 会导致通知被更新/覆盖。
    //display a notification with a plain title and body
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      'channel id', 'channel name', //这个会显示再安卓的通知设置里面
      channelDescription: 'updated channel description',
      importance: Importance.max,
      priority: Priority.high,
      ticker: 'ticker',
    );
    NotificationDetails notificationDetails =
        const NotificationDetails(android: androidNotificationDetails);
    await MgrLocalNotification.flutterLocalNotificationsPlugin
        .show(id, title, msg, notificationDetails,
            //paylaod 传递给点击通知后的回调函数
            payload: '我的item x');
  }

  //点击通知后的回调
  static onDidReceiveNotificationResponse(
      NotificationResponse notificationResponse) async {
    final String? payload = notificationResponse.payload;
    if (notificationResponse.payload != null) {
      print('notification payload: $payload');
    }
    print('点击通知回调');
    //点击通知导航到指定页面
    // await Navigator.push(
    //   context,
    //   MaterialPageRoute<void>(builder: (context) => SecondScreen(payload)),
    // );
  }
}

flutter docker

[!] Flutter (Channel stable, 3.24.0, on Ubuntu 24.04 LTS 6.8.0-40-generic, locale zh_CN.UTF-8)
    • Flutter version 3.24.0 on channel stable at /home/cruvie/cruvie-space/local-env/flutter
    ! The flutter binary is not on your path. Consider adding /home/cruvie/cruvie-space/local-env/flutter/bin to your path.
    ! The dart binary is not on your path. Consider adding /home/cruvie/cruvie-space/local-env/flutter/bin to your path.
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 80c2e84975 (3 周前), 2024-07-30 23:06:49 +0700
    • Engine revision b8800d88be
    • Dart version 3.5.0
    • DevTools version 2.37.2
    • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.

[!] Android toolchain - develop for Android devices (Android SDK version 35.0.0)
    • Android SDK at /home/cruvie/Android/Sdk
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/to/linux-android-setup for more details.

[✗] Chrome - develop for the web (Cannot find Chrome executable at google-chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.

[✗] Linux toolchain - develop for Linux desktop
    ✗ clang++ is required for Linux development.
      It is likely available from your distribution (e.g.: apt install clang), or can be downloaded from https://releases.llvm.org/
    • cmake version 3.28.3
    ✗ ninja is required for Linux development.
      It is likely available from your distribution (e.g.: apt install ninja-build), or can be downloaded from https://github.com/ninja-build/ninja/releases
    • pkg-config version 1.8.1
    ✗ GTK 3.0 development libraries are required for Linux development.
      They are likely available from your distribution (e.g.: apt install libgtk-3-dev)

[✓] Android Studio (version 2024.1)
    • Android Studio at /home/cruvie/.local/share/JetBrains/Toolbox/apps/android-studio
    • Flutter plugin version 81.0.2
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.11+0-17.0.11b1207.24-11852314)

[✓] IntelliJ IDEA Ultimate Edition (version 2024.2)
    • IntelliJ at /home/cruvie/.local/share/JetBrains/Toolbox/apps/intellij-idea-ultimate
    • Flutter plugin version 81.1.3
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.92.1)
    • VS Code at /usr/share/code
    • Flutter extension version 3.94.0

[✓] Connected device (2 available)
    • sdk gphone16k x86 64 (mobile) • emulator-5554 • android-x64 • Android 15 (API 35) (emulator)
    • Linux (desktop)               • linux         • linux-x64   • Ubuntu 24.04 LTS 6.8.0-40-generic

flutter_local_notifications version
17.2.2
failed on android 14 physical or android 15 emulator

@cruvie
Copy link
Author

cruvie commented Sep 13, 2024

@Lonyless hi, did you solve the problem?

@Lonyless
Copy link

@Lonyless hi, did you solve the problem?

Turns out the problem wasn’t caused by this package, but a bug in the emulator itself. Try running Android 11 to make sure

@richirisu
Copy link

richirisu commented Nov 6, 2024

I came across the same problem. It happens when trying to build the APK in release mode. Debug mode seems fine.

In my case, however, it happend after upgrading Android Studio from Koala to Ladybug. It seems that Koala is bundled with JDK17 and Ladybug JDK21. Making Flutter use JDK17 lets me build the APK the usual way (no blocking when starting the application).

Show Flutter Java version for building

flutter doctor -v

Change Flutter Java version for building

flutter config --jdk-dir "/Applications/Android Studio Koala.app/Contents/jbr/Contents/Home/"

By the way, I am initializing the FlutterLocalNotificationsPlugin in the main method.

EDIT: Building using JDK21 with coreLibraryDesugaringEnabled, and JDK17 without coreLibraryDesugaringEnabled.

@TheFinestArtist
Copy link

TheFinestArtist commented Nov 15, 2024

It took me so much time to figure this out. After I rollback the com.android.application dependency, everything works fine.

// Before
id "com.android.application" version "8.2.0" apply false
// After
id "com.android.application" version "8.7.2" apply false

@Levi-Lesches
Copy link
Contributor

I'd recommend not to immediately request permissions on launch, even though it is easier. Instead, request permissions after onboarding the user a bit, and having them request or confirm notifications. For example, web browsers will block permissions requests if they don't come from a user gesture

It's possible android is freaking out about this as well? I didn't actually look into it but either way I'd still recommend moving the permissions request

@MaikuB
Copy link
Owner

MaikuB commented Dec 31, 2024

@cruvie This isn't a bug but an issue with the code in your app and is actually working as expected. Since you call await MgrLocalNotification.init(); before runApp(const MyApp());, the logic you have in your code is waiting for all of the logic that includes getting the results of requesting permissions to finish before the app is rendered. This is one of the reasons why the example app does the permissions request as part of initState()

@MaikuB MaikuB closed this as completed Dec 31, 2024
@cruvie
Copy link
Author

cruvie commented Jan 2, 2025

@MaikuB thanks for your response, but after I move permission request to _MyHomePageState initState(), the problem still exists
I have update the code here https://github.com/cruvie/demo/blob/master/lib/local_notification.dart could you please have a quick look?
the key is

//bug await will block the app open in release mode
    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onDidReceiveNotificationResponse:
            ToolLocalNotification.onDidReceiveNotificationResponse);

if I remove await the app can open with no block but notification not work.

@Levi-Lesches
Copy link
Contributor

Levi-Lesches commented Jan 2, 2025

I'm confused -- this is the output I'm getting: your home screen with the notification popup in front. Is that not what you were expecting?

@cruvie
Copy link
Author

cruvie commented Jan 2, 2025

@Levi-Lesches do you run the app in release mode?
the key is await flutterLocalNotificationsPlugin.initializewill block app open, which means the app will stay start page like this
PixPin_2025-01-02_12-49-35

@Levi-Lesches
Copy link
Contributor

Levi-Lesches commented Jan 2, 2025

Okay, with flutter run --release, I could reproduce that. Removing the await reveals an error:

E/flutter (13907): [ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: PlatformException(invalid_icon, The resource app_icon could not be found. Please make sure it has been added as a drawable resource to your Android head project., null, null)
E/flutter (13907): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:646)
E/flutter (13907): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:334)
E/flutter (13907): <asynchronous suspension>
E/flutter (13907): #2      AndroidFlutterLocalNotificationsPlugin.initialize (package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:148)
E/flutter (13907): <asynchronous suspension>
E/flutter (13907): #3      MgrLocalNotification.init (package:demo/local_notification.dart:36)
E/flutter (13907): <asynchronous suspension>
E/flutter (13907): #4      main (package:demo/main.dart:11)
E/flutter (13907): <asynchronous suspension>

But I'm not sure why you're getting it because I can confirm that you have the image in the right folder. The example app works with the same flutter run --release

@Levi-Lesches

This comment was marked as outdated.

@cruvie
Copy link
Author

cruvie commented Jan 2, 2025

@Levi-Lesches thanks a lot, what a relief.

@MaikuB
Copy link
Owner

MaikuB commented Jan 10, 2025

Resource shrinking being enabled is default/standard/best practices so really shouldn't be off. It's part of the optimisation process in generation release builds. There was a section the setup guide around release build configuration to ensure resources are kept through that process. Looking at the repo shared, it looks like it wasn't followed

@Levi-Lesches
Copy link
Contributor

Good point -- I have both sections included, but I will clarify that disabled resource shrinking is a last-resort and the other method should be preferred whenever possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants