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

Open
cruvie opened this issue Aug 20, 2024 · 3 comments
Open

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.

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

3 participants