firebase / flutterfire

πŸ”₯ A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.63k stars 3.95k forks source link

πŸ› [firebase_messaging] When the application is terminated and a message from fcm received the main method is executed automatically! #9779

Closed hosseinkhojany closed 1 year ago

hosseinkhojany commented 1 year ago

Bug report

Describe the bug When the program is completely closed and I receive a message from fcm, the program's main function is executed automatically, and this is very bad for my program. I tested the firebase_messaging example and it works correctly, it is not starting the main method. Why is it happening in my code?

My code is similar to the implemented Git example https://github.com/firebase/flutterfire/tree/master/packages/firebase_messaging

Flutter doctor

Run flutter doctor and paste the output below:

Click To Expand ``` [βœ“] Flutter (Channel stable, 3.0.2, on Ubuntu 20.04.3 LTS 5.4.0-050400-generic, locale en_US.UTF-8) β€’ Flutter version 3.0.2 at /home/khoujani/Documents/flutter/3.0.3 β€’ Upstream repository https://github.com/flutter/flutter.git β€’ Framework revision cd41fdd495 (5 months ago), 2022-06-08 09:52:13 -0700 β€’ Engine revision f15f824b57 β€’ Dart version 2.17.3 β€’ DevTools version 2.12.2 [!] Android toolchain - develop for Android devices (Android SDK version 33.0.0) β€’ Android SDK at /usr/lib/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/docs/get-started/install/linux#android-setup for more details. [βœ“] Chrome - develop for the web β€’ Chrome at google-chrome [βœ“] Linux toolchain - develop for Linux desktop β€’ clang version 10.0.0-4ubuntu1 β€’ cmake version 3.16.3 β€’ ninja version 1.10.0 β€’ pkg-config version 0.29.1 [βœ“] Android Studio (version 2021.1) β€’ Android Studio at /home/khoujani/ANDROID/android-2021.1.1 β€’ Flutter plugin version 64.0.2 β€’ Dart plugin version 211.7798 β€’ Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822) [βœ“] VS Code β€’ VS Code at /snap/code/current β€’ Flutter extension version 3.44.0 [βœ“] Connected device (3 available) β€’ M2010J19CG (mobile) β€’ c0b33e21120 β€’ android-arm64 β€’ Android 10 (API 29) β€’ Linux (desktop) β€’ linux β€’ linux-x64 β€’ Ubuntu 20.04.3 LTS 5.4.0-050400-generic β€’ Chrome (web) β€’ chrome β€’ web-javascript β€’ Google Chrome 105.0.5195.125 [βœ“] HTTP Host Availability β€’ All required HTTP hosts are available ! Doctor found issues in 1 category. ```

Flutter dependencies

Run flutter pub deps -- --style=compact and paste the output below:

Click To Expand ``` Dart SDK 2.17.3 Flutter SDK 3.0.2 myelin 2.1.4+159 dependencies: - audio_service 0.18.7 [audio_service_platform_interface audio_service_web audio_session rxdart flutter_cache_manager clock js flutter flutter_web_plugins] - background_fetch 1.0.1 [flutter] - cached_network_image 3.2.0 [flutter flutter_cache_manager octo_image cached_network_image_platform_interface cached_network_image_web] - chewie 1.3.5 [cupertino_icons flutter provider video_player wakelock] - crop_image 1.0.2 [flutter meta] - custom_pop_up_menu 1.2.3+1 [flutter] - dio 4.0.6 [http_parser path] - division 0.9.0 [flutter] - email_launcher 1.1.1 [flutter] - emoji_picker_flutter 1.3.0 [flutter shared_preferences] - equatable 2.0.5 [collection meta] - file_picker 4.6.1 [flutter flutter_web_plugins flutter_plugin_android_lifecycle plugin_platform_interface ffi path win32] - firebase_analytics 8.3.4 [firebase_analytics_platform_interface firebase_analytics_web firebase_core flutter meta] - firebase_core 1.24.0 [firebase_core_platform_interface firebase_core_web flutter meta] - firebase_messaging 13.1.0 [firebase_core firebase_core_platform_interface firebase_messaging_platform_interface firebase_messaging_web flutter meta] - flutter 0.0.0 [characters collection material_color_utilities meta vector_math sky_engine] - flutter_cache_manager 3.3.0 [clock collection file flutter http path path_provider pedantic rxdart sqflite uuid] - flutter_linear_datepicker 2.0.3 [flutter shamsi_date] - flutter_local_notifications 11.0.1 [clock flutter flutter_local_notifications_linux flutter_local_notifications_platform_interface timezone] - flutter_picker 2.0.5 [flutter] - flutter_ringtone_player 3.2.0 [flutter path_provider] - flutter_staggered_animations 1.0.0 [flutter] - flutter_staggered_grid_view 0.4.1 [flutter] - flutter_svg 0.22.0 [flutter meta path_drawing vector_math xml] - flutter_swipe_action_cell 2.2.3 [flutter] - flutter_time_picker_spinner 2.0.0 [flutter] - flutter_typeahead 3.2.7 [flutter flutter_keyboard_visibility] - get 4.6.5 [flutter] - get_it 7.2.0 [async collection] - hive 2.2.3 [meta crypto] - html 0.15.0 [csslib source_span] - http 0.13.5 [async http_parser meta path] - image_cropper 2.0.3 [flutter image_cropper_platform_interface image_cropper_for_web] - image_picker 0.7.5+4 [flutter flutter_plugin_android_lifecycle image_picker_platform_interface image_picker_for_web] - image_picker_for_web 2.1.8 [flutter flutter_web_plugins image_picker_platform_interface] - iran_appmarket 0.4.1 [flutter get_version android_intent] - just_audio 0.9.28 [just_audio_platform_interface just_audio_web audio_session rxdart path path_provider async uuid crypto meta flutter] - keyboard_avoider 0.1.2 [flutter] - laravel_flutter_pusher 0.0.4 [flutter json_annotation] - loading_overlay 0.3.0 [flutter] - map_launcher 2.3.0+1 [flutter] - marquee_text 2.5.0+1 [flutter] - marquee_widget 1.2.0 [flutter] - package_info 2.0.2 [flutter] - path 1.8.1 - path_provider 2.0.11 [flutter path_provider_android path_provider_ios path_provider_linux path_provider_macos path_provider_platform_interface path_provider_windows] - permission_handler 8.3.0 [flutter meta permission_handler_platform_interface] - persian_datepicker 1.3.1 [flutter] - photo_manager 2.2.1 [flutter] - photo_view 0.12.0 [flutter] - pin_code_fields 7.4.0 [flutter] - provider 6.0.3 [collection flutter nested] - pull_to_refresh 2.0.0 [flutter] - record 3.0.4 [flutter record_platform_interface record_web] - restart_app 1.1.0+1 [flutter plugin_platform_interface flutter_web_plugins] - scrollable_positioned_list 0.2.3 [flutter collection] - shamsi_date 0.15.0 - share 2.0.4 [meta mime flutter] - shared_preferences 2.0.15 [flutter shared_preferences_android shared_preferences_ios shared_preferences_linux shared_preferences_macos shared_preferences_platform_interface shared_preferences_web shared_preferences_windows] - shimmer 2.0.0 [flutter] - sms_autofill 2.2.0 [pin_input_text_field flutter] - sqflite 2.0.2+1 [flutter sqflite_common path] - store_checker 0.1.0 [flutter] - syncfusion_flutter_charts 19.4.56 [flutter intl vector_math syncfusion_flutter_core] - toast 0.1.5 [flutter] - touchable 1.0.2 [flutter] - url_launcher 6.1.5 [flutter url_launcher_android url_launcher_ios url_launcher_linux url_launcher_macos url_launcher_platform_interface url_launcher_web url_launcher_windows] - video_player 2.4.7 [flutter html video_player_android video_player_avfoundation video_player_platform_interface video_player_web] - wc_flutter_share 0.4.0 [flutter path_provider] - weekday_selector 1.1.0 [flutter] dev dependencies: - flutter_flavorizr 2.1.3 [flutter archive args checked_yaml collection image io json_annotation sprintf xml yaml] - flutter_launcher_icons 0.9.3 [args image path yaml] - flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters charcode collection matcher material_color_utilities meta source_span stream_channel string_scanner term_glyph] - hive_test 1.0.1 [flutter hive path] transitive dependencies: - _flutterfire_internals 1.0.2 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta] - android_intent 2.0.2 [flutter platform meta] - archive 3.3.1 [crypto path] - args 2.3.1 - async 2.8.2 [collection meta] - audio_service_platform_interface 0.1.0 [flutter plugin_platform_interface meta] - audio_service_web 0.1.1 [audio_service_platform_interface rxdart js flutter flutter_web_plugins] - audio_session 0.1.10 [flutter flutter_web_plugins rxdart meta] - boolean_selector 2.1.0 [source_span string_scanner] - cached_network_image_platform_interface 1.0.0 [flutter flutter_cache_manager] - cached_network_image_web 1.0.1 [flutter flutter_cache_manager cached_network_image_platform_interface] - characters 1.2.0 - charcode 1.3.1 - checked_yaml 2.0.1 [json_annotation source_span yaml] - clock 1.1.0 - cloud_firestore_platform_interface 5.7.7 [_flutterfire_internals collection firebase_core flutter meta plugin_platform_interface] - cloud_firestore_web 2.8.10 [_flutterfire_internals cloud_firestore_platform_interface collection firebase_core firebase_core_web flutter flutter_web_plugins js] - collection 1.16.0 - cross_file 0.3.3+1 [js meta] - crypto 3.0.2 [typed_data] - csslib 0.17.2 [source_span] - cupertino_icons 1.0.5 - dbus 0.7.3 [args ffi meta xml] - fake_async 1.3.0 [clock collection] - ffi 1.2.1 - file 6.1.4 [meta path] - firebase 9.0.3 [http http_parser js] - firebase_analytics_platform_interface 2.0.1 [flutter meta] - firebase_analytics_web 0.3.0+1 [firebase firebase_analytics_platform_interface flutter flutter_web_plugins meta] - firebase_core_platform_interface 4.5.1 [collection flutter flutter_test meta plugin_platform_interface] - firebase_core_web 1.7.3 [firebase_core_platform_interface flutter flutter_web_plugins js meta] - firebase_messaging_platform_interface 4.2.0 [_flutterfire_internals firebase_core flutter meta plugin_platform_interface] - firebase_messaging_web 3.2.0 [_flutterfire_internals firebase_core firebase_core_web firebase_messaging_platform_interface flutter flutter_web_plugins js meta] - flutter_blurhash 0.7.0 [flutter] - flutter_keyboard_visibility 5.3.0 [meta flutter_keyboard_visibility_platform_interface flutter_keyboard_visibility_web flutter] - flutter_keyboard_visibility_platform_interface 2.0.0 [flutter meta plugin_platform_interface] - flutter_keyboard_visibility_web 2.0.0 [flutter_keyboard_visibility_platform_interface flutter_web_plugins flutter] - flutter_local_notifications_linux 1.0.0 [flutter flutter_local_notifications_platform_interface dbus path xdg_directories] - flutter_local_notifications_platform_interface 6.0.0 [flutter plugin_platform_interface] - flutter_plugin_android_lifecycle 2.0.7 [flutter] - flutter_web_plugins 0.0.0 [flutter js characters collection material_color_utilities meta vector_math] - get_version 0.0.8+4 [package_info flutter] - http_parser 4.0.1 [collection source_span string_scanner typed_data] - image 3.1.3 [archive meta xml] - image_cropper_for_web 0.0.4 [flutter flutter_web_plugins image_cropper_platform_interface js] - image_cropper_platform_interface 2.0.0 [flutter plugin_platform_interface http] - image_picker_platform_interface 2.6.1 [cross_file flutter http plugin_platform_interface] - intl 0.17.0 [clock path] - io 1.0.3 [meta path string_scanner] - js 0.6.4 - json_annotation 4.6.0 [meta] - just_audio_platform_interface 4.2.0 [flutter plugin_platform_interface] - just_audio_web 0.4.7 [just_audio_platform_interface flutter flutter_web_plugins] - matcher 0.12.11 [stack_trace] - material_color_utilities 0.1.4 - meta 1.7.0 - mime 1.0.2 - nested 1.0.0 [flutter] - octo_image 1.0.2 [flutter flutter_blurhash] - path_drawing 0.5.1+1 [vector_math meta path_parsing flutter] - path_parsing 0.2.1 [vector_math meta] - path_provider_android 2.0.20 [flutter path_provider_platform_interface] - path_provider_ios 2.0.11 [flutter path_provider_platform_interface] - path_provider_linux 2.1.7 [ffi flutter path path_provider_platform_interface xdg_directories] - path_provider_macos 2.0.6 [flutter path_provider_platform_interface] - path_provider_platform_interface 2.0.4 [flutter platform plugin_platform_interface] - path_provider_windows 2.0.7 [ffi flutter path path_provider_platform_interface win32] - pedantic 1.11.1 - permission_handler_platform_interface 3.7.0 [flutter meta plugin_platform_interface] - petitparser 4.4.0 [meta] - pin_input_text_field 4.2.0 [flutter] - platform 3.1.0 - plugin_platform_interface 2.1.2 [meta] - process 4.2.4 [file path platform] - record_platform_interface 0.2.0 [flutter plugin_platform_interface] - record_web 0.2.1 [flutter flutter_web_plugins record_platform_interface] - rxdart 0.26.0 - shared_preferences_android 2.0.13 [flutter shared_preferences_platform_interface] - shared_preferences_ios 2.1.1 [flutter shared_preferences_platform_interface] - shared_preferences_linux 2.1.1 [file flutter path path_provider_linux path_provider_platform_interface shared_preferences_platform_interface] - shared_preferences_macos 2.0.4 [flutter shared_preferences_platform_interface] - shared_preferences_platform_interface 2.1.0 [flutter plugin_platform_interface] - shared_preferences_web 2.0.4 [flutter flutter_web_plugins shared_preferences_platform_interface] - shared_preferences_windows 2.1.1 [file flutter path path_provider_platform_interface path_provider_windows shared_preferences_platform_interface] - sky_engine 0.0.99 - source_span 1.8.2 [collection path term_glyph] - sprintf 6.0.2 - sqflite_common 2.2.1+1 [synchronized path meta] - stack_trace 1.10.0 [path] - stream_channel 2.1.0 [async] - string_scanner 1.1.0 [charcode source_span] - syncfusion_flutter_core 19.4.56 [vector_math flutter] - synchronized 3.0.0+3 - term_glyph 1.2.0 - test_api 0.4.9 [async boolean_selector collection meta source_span stack_trace stream_channel string_scanner term_glyph matcher] - timezone 0.9.0 [path] - typed_data 1.3.0 [collection] - url_launcher_android 6.0.18 [flutter url_launcher_platform_interface] - url_launcher_ios 6.0.17 [flutter url_launcher_platform_interface] - url_launcher_linux 3.0.1 [flutter url_launcher_platform_interface] - url_launcher_macos 3.0.1 [flutter url_launcher_platform_interface] - url_launcher_platform_interface 2.1.0 [flutter plugin_platform_interface] - url_launcher_web 2.0.13 [flutter flutter_web_plugins url_launcher_platform_interface] - url_launcher_windows 3.0.1 [flutter url_launcher_platform_interface] - uuid 3.0.6 [crypto] - vector_math 2.1.2 - video_player_android 2.3.9 [flutter video_player_platform_interface] - video_player_avfoundation 2.3.5 [flutter video_player_platform_interface] - video_player_platform_interface 5.1.4 [flutter plugin_platform_interface] - video_player_web 2.0.12 [flutter flutter_web_plugins video_player_platform_interface] - wakelock 0.6.2 [flutter meta wakelock_macos wakelock_platform_interface wakelock_web wakelock_windows] - wakelock_macos 0.4.0 [flutter flutter_web_plugins wakelock_platform_interface] - wakelock_platform_interface 0.3.0 [flutter meta] - wakelock_web 0.4.0 [flutter flutter_web_plugins js wakelock_platform_interface] - wakelock_windows 0.2.0 [flutter wakelock_platform_interface win32] - win32 2.5.2 [ffi] - xdg_directories 0.2.0+2 [meta path process] - xml 5.3.1 [collection meta petitparser] - yaml 3.1.1 [collection source_span string_scanner] ```

danagbemava-nc commented 1 year ago

Hi @hosseinkhojany, since the plugin example works as expected this is likely an issue with how you configured your application. Can you share your code? As without a complete minimal reproducible code sample, we cannot diagnose this issue.

hosseinkhojany commented 1 year ago

No, unfortunately, I can't share the code, but this problem is very strange and I have to restart the program to solve the problem. If I don't restart, the program shows a black screen.

hosseinkhojany commented 1 year ago

The only difference between my code and your code is that I put the function to receive the message when the app is closed in another class not in main class. Can it be from this?

danagbemava-nc commented 1 year ago

Hi @hosseinkhojany, does your backgroundMessageHandler conform to the rules specified in https://firebase.flutter.dev/docs/messaging/usage#background-messages?

hosseinkhojany commented 1 year ago
my main.dart ```dart import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:background_fetch/background_fetch.dart'; import 'package:dio/dio.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_analytics/observer.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:get/get.dart'; import 'package:hive/hive.dart'; import 'package:myelin/config/app_globals.dart'; import 'package:myelin/config/colors.dart'; import 'package:myelin/config/images.dart'; import 'package:myelin/config/page_routes.dart'; import 'package:myelin/config/providers.dart'; import 'package:myelin/config/size_config.dart'; import 'package:myelin/font_size_notifier.dart'; import 'package:myelin/screens/splash/view/view.dart'; import 'package:myelin/services/network/check_certificate.dart'; import 'package:myelin/services/network/logging_interceptor.dart'; import 'package:myelin/services/storage/helpers/meditation_helper.dart'; import 'package:myelin/services/storage/local_storage.dart'; import 'package:myelin/services/storage/notification/notification_db_helper.dart'; import 'package:myelin/services/utils/background.dart'; import 'package:myelin/services/utils/notification_state_handler.dart'; import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; // ignore: unnecessary_import import 'package:flutter/foundation.dart' show kIsWeb; import 'config/firebase_json_config.dart'; import 'config/themes.dart'; import 'services/storage/sqlite_database.dart'; import 'dart:math'; Future main() async { AppGlobals.appFlavor = Flavors.MYKET; await runBlock((widget){ runApp(widget); }); } Future runBlock(Function(Widget) run) async { SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle( statusBarColor: AppColors.buttonColor.withOpacity(0.3))); WidgetsFlutterBinding.ensureInitialized(); try { await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform); } on Exception catch (e) { e.printError(); } FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackground); if (!kIsWeb) { await config(); } // await LocalStorage.set(LocalStorage.keyToken, 'NGB1wjCHOKGrmkWdu1FfBgWQTdh8KbihUfNbyWcna4chtSMHfBX8Zqw6N3d2' , Types.STRING); // await LocalStorage.set(LocalStorage.keyToken, 'exc4BVhcfJpjaQBOh85WLv5gh6ww8fSNC3cIUVWUNR737nzh0w0jHlNFFODB' , Types.STRING); // await LocalStorage.set(LocalStorage.keyIntro, true , Types.BOOL); // if (kIsWeb) { // setWindowTitle('App title'); // setWindowMinSize(const Size(700, 500)); // setWindowMaxSize(Size.infinite); // } AppGlobals.placeholder = (await rootBundle.load(AppImages.checkIcon)).buffer.asUint8List(); // AppGlobals.baseApi = await LocalStorage.get(LocalStorage.baseApi, Types.STRING); if (!kIsWeb) { final _appDirectory = await getApplicationDocumentsDirectory(); Hive.init(_appDirectory.path); await DatabaseHelper.init( [ MeditationHelper.createTableQuery, NotificationDbHelper.createTableQueryNotification, ], ); } SizeConfig().init(); print('SizeConfig.screenWidth : ${SizeConfig.screenWidth}'); print('SizeConfig.screenHeight : ${SizeConfig.screenHeight}'); AppGlobals.dio = Dio(); AppGlobals.dio.interceptors.add(LoggingInterceptor()); final multiProvider = Center( child: SizedBox( width: SizeConfig.screenWidth, height: SizeConfig.screenHeight, child: MultiProvider( providers: MultiAppProvider.providers(), child: MyApp(), )), ); runZonedGuarded(() { HttpOverrides.global = new MyelinHttpOverride(); run.call(multiProvider); }, (error, stackTrace) {}); if (!kIsWeb) { try { BackgroundFetch.registerHeadlessTask( backgroundFetchTaskHeadless, ); } on Exception catch (e) { e.printError(); } } } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State { FontSizeNotifier _fontSizeNotifier; @override void initState() { _fontSizeNotifier = FontSizeNotifier(TextFontSize.Medium); super.initState(); toggleAppRunning(true); } @override void dispose() { _fontSizeNotifier.dispose(); // getIt().dispose(); toggleAppRunning(false); super.dispose(); } Future toggleAppRunning(bool running) async { await LocalStorage.set(LocalStorage.appIsRunning, running, Types.BOOL); } @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitDown, DeviceOrientation.portraitUp, ]); return ChangeNotifierProvider.value( value: _fontSizeNotifier, child: Consumer( builder: (context, data, child) { return ClipRect( child: GetMaterialApp( title: 'Myelin', shortcuts: { LogicalKeySet(LogicalKeyboardKey.space): ActivateIntent(), }, scrollBehavior: MyCustomScrollBehavior(), debugShowCheckedModeBanner: false, theme: AppThemes.light(data.getFontMagnitude()), home: SplashView(), builder: (context, app) { // if (kIsWeb) // return MediaQuery( // data: MediaQueryData(), // child: app, // ); return app; }, routes: PageRoutes.routes(), ), ); }, ), ); } // Widget _buildWebApp(_, Widget app) { // return Navigator( // onGenerateRoute: (settings) => MaterialPageRoute( // builder: (context) => WebApp( // app: app, // ), // ), // ); // } } class MyCustomScrollBehavior extends MaterialScrollBehavior { // Override behavior methods and getters like dragDevices // for web app @override Set get dragDevices => { PointerDeviceKind.touch, PointerDeviceKind.mouse, }; } class WebApp extends StatefulWidget { final Widget app; const WebApp({Key key, this.app}) : super(key: key); @override _WebAppState createState() => _WebAppState(); } class _WebAppState extends State { @override void initState() { super.initState(); } WebAppSizeData _calculateSizeData(Size appSize) { final width = appSize.height * 0.75; return WebAppSizeData( width: min(width, appSize.width), height: appSize.height, horizontalMargin: max((appSize.width - width) / 2, 0.0), ); } Widget _buildWebApp() { final mediaQueryData = MediaQuery.of(context); final webAppSizeData = _calculateSizeData(mediaQueryData.size); final themeData = Theme.of(context); return Stack( children: [ Container( height: double.infinity, width: double.infinity, color: Colors.white60, ), MediaQuery( data: mediaQueryData.copyWith( size: Size( webAppSizeData.width, webAppSizeData.height, ), ), child: Container( decoration: BoxDecoration( color: themeData.scaffoldBackgroundColor, boxShadow: [ BoxShadow( color: Colors.black87, offset: const Offset(0.0, 8.0), blurRadius: 13.0, ) ], ), margin: EdgeInsets.symmetric( horizontal: webAppSizeData.horizontalMargin, ), child: ClipRect(child: widget.app), ), ), ], ); } @override Widget build(BuildContext context) { return _buildWebApp(); } } class WebAppSizeData { final double width; final double height; final double horizontalMargin; WebAppSizeData({ this.width = double.infinity, this.height = double.infinity, this.horizontalMargin = 0.0, }); } ```
My notification_state_handler.dart that onBackgroundHandler is defined here ```dart import 'dart:convert'; import 'dart:io'; import 'dart:math'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:get/get.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart'; import 'package:myelin/config/api_routes.dart'; import 'package:myelin/config/app_globals.dart'; import 'package:myelin/services/storage/local_storage.dart'; import 'package:myelin/services/storage/notification/notification_db_hive.dart'; import 'package:myelin/services/utils/firebase_messaging_navigator.dart'; import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; import 'package:restart_app/restart_app.dart'; import '../../config/firebase_json_config.dart'; import '../../screens/doctor_reminder/view.dart'; import '../../screens/medication_reminder_new/controller.dart'; import '../../screens/medication_reminder_new/view_reminder.dart'; RemoteMessage newMessage = new RemoteMessage(); AndroidNotificationChannel fcmChannel = AndroidNotificationChannel( 'high_importance_channel', // id 'High Importance Notifications', // title description: 'This channel is used for important notifications.', // description importance: Importance.high, ); AndroidNotificationChannel reminderChannel = AndroidNotificationChannel( 'com.dfa.flutterchatdemo', // id 'High Importance Notifications for reminder', // title description: 'This channel is used for important notifications for reminder.', // description importance: Importance.high, ); FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); bool isFlutterLocalNotificationsInitialized = false; void onLocalNotificationTappedHandle(BuildContext context, String payload) { if (payload != null) { print("PAYLOAD: " + payload); } else { print("PAYLOAD is null"); } if (payload != null) { if (payload == "medic") { Navigator.of(context).push( MaterialPageRoute( builder: (context) => ChangeNotifierProvider( create: (context) => ReminderController(), lazy: false, child: Material(child: MedicationReminderView()), ), ), ); return; } else if (payload == "doctor") { Navigator.of(context).push( MaterialPageRoute( builder: (context) => DoctorReminder(), ), ); return; } AppGlobals.initialRoute = null; } onFcmNotificationTapped(context, payload); } bool fcmNotificaionTappedHandled = false; void onFcmNotificationTapped(BuildContext context, String payload) async { if (!fcmNotificaionTappedHandled) { fcmNotificaionTappedHandled = true; FirebaseMessagingNavigator.navigator( context: context, data: jsonDecode(payload)); await FirebaseMessaging.instance.requestPermission( sound: true, badge: true, alert: true, announcement: false, carPlay: false, criticalAlert: false, provisional: false, ); } } Future config() async { try { if (isFlutterLocalNotificationsInitialized) { return; } fcmChannel = const AndroidNotificationChannel( 'high_importance_channel', // id 'High Importance Notifications', // title description: 'This channel is used for important notifications.', // description importance: Importance.high, ); reminderChannel = const AndroidNotificationChannel( 'com.dfa.flutterchatdemo', // id 'High Importance Notifications', // title description: 'This channel is used for important notifications.', // description importance: Importance.high, ); flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(fcmChannel); await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(reminderChannel); await FirebaseMessaging.instance .setForegroundNotificationPresentationOptions( alert: true, badge: true, sound: true, ); isFlutterLocalNotificationsInitialized = true; } on Exception catch (e) { debugPrint("$e"); } } Future showNotification({RemoteMessage message}) async { print("showNotification"+jsonEncode(message.data)); Future.delayed(Duration(milliseconds: 200), () { try{ flutterLocalNotificationsPlugin.show( Random().nextInt(1000000), message.data['title'], message.data['body'], NotificationDetails( android: AndroidNotificationDetails( fcmChannel.id, fcmChannel.name, channelDescription: fcmChannel.description, icon: "@mipmap/ic_stat_logo", playSound: true, enableVibration: true, priority: Priority.high, channelShowBadge: true, importance: Importance.high, ), iOS: DarwinNotificationDetails( presentAlert: true, presentBadge: true, presentSound: true, ), ), payload: jsonEncode(message.data), ); }on Exception catch(e){ e.printError(); } }); } Future _downloadAndSaveFile(String url, String fileName) async { try { final Directory directory = await getApplicationDocumentsDirectory(); final String filePath = '${directory.path}/$fileName'; if (!(await File(filePath).exists())) { final response = await get(Uri.parse(url)); final File file = File(filePath); List fileBytes = await convertImageFileToCustomBitmapDescriptor(response.bodyBytes) ?? response.bodyBytes; await file.writeAsBytes(fileBytes); return base64Encode(fileBytes); } else { return base64Encode(File.fromUri(Uri.parse(filePath)).readAsBytesSync()); } } on Exception catch (e) { e.printError(); return null; } } Future> convertImageFileToCustomBitmapDescriptor( Uint8List imageUint8List, {int size = 150, bool addBorder = false, Color borderColor = Colors.white, double borderSize = 10, Color titleColor = Colors.white, Color titleBackgroundColor = Colors.black}) async { final ui.PictureRecorder pictureRecorder = ui.PictureRecorder(); final Canvas canvas = Canvas(pictureRecorder); final Paint paint = Paint()..color; final double radius = size / 2; final Path clipPath = Path(); clipPath.addRRect(RRect.fromRectAndRadius( Rect.fromLTWH(0, 0, size.toDouble(), size.toDouble()), Radius.circular(100))); clipPath.addRRect(RRect.fromRectAndRadius( Rect.fromLTWH(0, size * 8 / 10, size.toDouble(), size * 3 / 10), Radius.circular(100))); canvas.clipPath(clipPath); final ui.Codec codec = await ui.instantiateImageCodec(imageUint8List); final ui.FrameInfo imageFI = await codec.getNextFrame(); paintImage( canvas: canvas, rect: Rect.fromLTWH(0, 0, size.toDouble(), size.toDouble()), image: imageFI.image); if (addBorder) { //draw Border paint..color = borderColor; paint..style = PaintingStyle.stroke; paint..strokeWidth = borderSize; canvas.drawCircle(Offset(radius, radius), radius, paint); } final _image = await pictureRecorder.endRecording().toImage(size, (size * 1.1).toInt()); final data = await _image.toByteData(format: ui.ImageByteFormat.png); return data.buffer.asUint8List(); } Future showGroupedNotifications() async { print("showGroupedNotifications"); flutterLocalNotificationsPlugin.cancelAll(); Future.delayed(Duration(milliseconds: 1000), () async { flutterLocalNotificationsPlugin.cancelAll(); const String groupKey = 'chats_groupKey'; Map> messages = (await getListMessages()); int counter = 0; (messages).forEach((String key, List listMessages) async { String image = await _downloadAndSaveFile( "https://" + jsonDecode(listMessages[0])["avatar"], jsonDecode(listMessages[0])["avatar"].toString().split("/")[ jsonDecode(listMessages[0])["avatar"] .toString() .split("/") .length - 1]); // String image = await _downloadAndSaveFile(ApiRoutes.IMAGE_URL+jsonDecode(listMessages[0])["avatar"], jsonDecode(listMessages[0])["avatar"].toString().split("/")[jsonDecode(listMessages[0])["avatar"].toString().split("/").length - 1]); String listGroupMessages = ""; String aMessage = ""; int count = 0; for (String remoteMessage in listMessages) { if (count == 0) { listGroupMessages += (jsonDecode(remoteMessage)["body"]); aMessage = remoteMessage; } else if (count == 7) { break; } else if (listMessages.length - 1 == count) { listGroupMessages += "\n" + (jsonDecode(remoteMessage)["body"]); break; } else { listGroupMessages += "\n" + (jsonDecode(remoteMessage)["body"]); } count++; } String chatName = ""; if (jsonDecode(aMessage)["group_name"].toString() != null) { chatName = jsonDecode(aMessage)["group_name"].toString(); } else { chatName = jsonDecode(aMessage)["display_name"].toString(); } AndroidNotificationDetails notificationAndroidSpecifics = AndroidNotificationDetails( fcmChannel.id, fcmChannel.name, category: AndroidNotificationCategory.message, channelDescription: "high_importance", importance: Importance.max, priority: Priority.high, groupKey: groupKey, styleInformation: MessagingStyleInformation( image != null ? Person( name: chatName, key: jsonDecode(aMessage)["chatable_id"].toString(), icon: ByteArrayAndroidIcon.fromBase64String(image), ) : Person( name: chatName, key: jsonDecode(aMessage)["chatable_id"].toString(), ), groupConversation: true, conversationTitle: '', messages: [ Message( listGroupMessages, DateTime.now(), image != null ? Person( name: chatName, key: jsonDecode(aMessage)["chatable_id"].toString() + jsonDecode(aMessage)["display_name"].toString(), icon: ByteArrayAndroidIcon.fromBase64String(image), ) : Person( name: chatName, key: jsonDecode(aMessage)["chatable_id"].toString() + jsonDecode(aMessage)["display_name"].toString(), ), ) ]), ); NotificationDetails notificationPlatformSpecifics = NotificationDetails(android: notificationAndroidSpecifics); await flutterLocalNotificationsPlugin.show( Random().nextInt(1000000), '${jsonDecode(listMessages[0])['group_name'] != null ? jsonDecode(listMessages[0])['group_name'] : jsonDecode(listMessages[0])['display_name']}', jsonDecode(listMessages[0])['body'] + " ...", notificationPlatformSpecifics, payload: listMessages[0], ); if (counter == messages.length - 1) { List linesChannels = []; InboxStyleInformation inboxStyleInformationChanneNames = InboxStyleInformation(linesChannels, contentTitle: 'New messages preparing', summaryText: ''); AndroidNotificationDetails androidNotificationDetailsChannels = AndroidNotificationDetails(fcmChannel.id, fcmChannel.name, channelDescription: fcmChannel.description, styleInformation: inboxStyleInformationChanneNames, groupKey: groupKey, setAsGroupSummary: true); NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetailsChannels); await flutterLocalNotificationsPlugin.show( Random().nextInt(1000000), '', '', notificationDetails); } counter++; }); }); } @pragma('vm:entry-point') Future firebaseMessagingBackground(RemoteMessage message) async { print("firebaseMessagingBackground: " + message.data.toString()); try { // if(Firebase.apps.isEmpty){ await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform); // } } on Exception catch (e) { e.printError(); } await config(); await LocalStorage.set(LocalStorage.fcmReceived, true, Types.BOOL); await LocalStorage.set(LocalStorage.appIsRunning, false, Types.BOOL); handleNewFcmReceived(message, false); } void handleNewFcmReceived(RemoteMessage message, bool fromFourground) async { switch (message.data['page']) { case "chat": print("fucking chat"); final _appDirectory = await getApplicationDocumentsDirectory(); Hive.init(_appDirectory.path); await addMessage( (message.data["chatable_id"]).toString(), jsonEncode(message.data)); showGroupedNotifications(); break; case "mission": case "birthday": if(fromFourground){ showNotification(message: message); print("fucking cron job"); } break; case "connect": case "achievements": case "medal": case "club": print("fucking not cron job"); showNotification(message: message); break; } } cancelNotificationWithId(String id) async { flutterLocalNotificationsPlugin.getActiveNotifications().then((value) async { bool removed = false; for (var notification in value) { if (removed) { break; } String chatableIdNotificaction = jsonDecode(notification.payload)['chatable_id']; (await getListMessages()) .forEach((String key, List listMessages) async { String chatableId = jsonDecode(listMessages[0])['chatable_id']; if (chatableIdNotificaction == chatableId) { flutterLocalNotificationsPlugin.cancel(notification.id); removed = true; } }); } }); } ```
danagbemava-nc commented 1 year ago

Hi @hosseinkhojany, can you try producing a minimal sample code from your project? Maybe that could help us discover why your backgroundMessageHandler is not working properly

hosseinkhojany commented 1 year ago

When I removed this line of code from the manifest, the main function is no longer executed and the behavior of the program is fixed

    <service
        android:name="com.ryanheise.audioservice.AudioService"
        android:exported="true"
        tools:ignore="Instantiatable">
        <intent-filter>
            <action android:name="android.media.browse.MediaBrowserService" />
        </intent-filter>
    </service>

package: audio_service: ^0.18.7

danagbemava-nc commented 1 year ago

Hi @hosseinkhojany, if that is the case, I think you should report this issue on the audio_service repo so they can investigate it.
Given that this issue seems to be caused by a third-party plugin, I'll be closing this issue.

If you are redirected here after reporting this on their end, kindly leave a comment below and I will reopen this issue.

Thank you