Skip to content

[firebase_messaging] Background Message Handler not called #1590

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

Closed
mahmoud0123 opened this issue Dec 10, 2019 · 26 comments
Closed

[firebase_messaging] Background Message Handler not called #1590

mahmoud0123 opened this issue Dec 10, 2019 · 26 comments
Labels
impact: crowd Affects many people, though not necessarily a specific customer with an assigned label. (P2) plugin: messaging type: bug Something isn't working

Comments

@mahmoud0123
Copy link

mahmoud0123 commented Dec 10, 2019

Hello, Iam developing an app for pushing notifications from fcm, when the app in background or terminated and receive notification i need to save the data of this notification local in (sqlit), without click on the notification or re-open the app gain. the background message handler not called or read the message when the app in background. help please.

NotificationHandler.dart

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
new FlutterLocalNotificationsPlugin();

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
  print("onBackgroundMessage: $message");
  //_showBigPictureNotification(message);
  return Future<void>.value();
}


Future onSelectNotification(String payload) async {

}

class NotificationHandler {
  FirebaseMessaging _fcm = FirebaseMessaging();
  StreamSubscription iosSubscription;
  static final NotificationHandler _singleton =
  new NotificationHandler._internal();

  factory NotificationHandler() {
    return _singleton;
  }
  NotificationHandler._internal();

  initializeFcmNotification() async {
    var initializationSettingsAndroid =
    new AndroidInitializationSettings('mipmap/ic_launcher');
    var initializationSettingsIOS = new IOSInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification);
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onSelectNotification);

    if (Platform.isIOS) {
      iosSubscription = _fcm.onIosSettingsRegistered.listen((data) {
        // save the token  OR subscribe to a topic here
      });

      _fcm.requestNotificationPermissions(IosNotificationSettings());
    } else {
      _saveDeviceToken();
    }

    _fcm.configure(
      onMessage: (Map<String, dynamic> message) async {
        print(message);
      },
      onBackgroundMessage:
      TargetPlatform.iOS == 'ios' ? null : myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );
  }

  /// Get the token, save it to the database for current user
  _saveDeviceToken() async {
    String fcmToken = await _fcm.getToken();
    print("FCM_TOKEN: $fcmToken");
  }

  Future<void> onDidReceiveLocalNotification(
      int id, String title, String body, String payload) async {
    // display a dialog with the notification details, tap ok to go to another page
  }
}
@iapicca iapicca changed the title Background Message Handler not called when the app in background [firebase_messaging] Background Message Handler not called Dec 10, 2019
@iapicca
Copy link

iapicca commented Dec 10, 2019

Hi @mahmoud0123
can you please provide your updated flutter doctor -v?
Thank you

@iapicca iapicca added blocked: customer-response Waiting for customer response, e.g. more information was requested. type: bug Something isn't working labels Dec 10, 2019
@mahmoud0123
Copy link
Author

mahmoud0123 commented Dec 10, 2019

Hi @mahmoud0123
can you please provide your updated flutter doctor -v?
Thank you

Hi @iapicca thanks for your response here is flutter doctor

Mahmouds-MacBook-Pro:~ mahmoudabdelaziz$ flutter doctor -v
[✓] Flutter (Channel stable, v1.9.1+hotfix.4, on Mac OS X 10.14.4 18E226, locale en-US)
• Flutter version 1.9.1+hotfix.4 at /Users/mahmoudabdelaziz/Desktop/flutter
• Framework revision cc949a8e8b (2 months ago), 2019-09-27 15:04:59 -0700
• Engine revision b863200c37
• Dart version 2.5.0

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
• Android SDK at /Users/mahmoudabdelaziz/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-28, build-tools 28.0.3
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.0)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.0, Build version 11A420a
• CocoaPods version 1.8.4

[!] Android Studio (version 3.4)
• Android Studio at /Applications/Android Studio.app/Contents
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1343-b01)

[✓] IntelliJ IDEA Community Edition (version 2018.3.3)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
• Flutter plugin version 31.3.4
• Dart plugin version 183.5153.38

[✓] Connected device (1 available)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 9 (API 28) (emulator)

! Doctor found issues in 1 category.

@LinusU
Copy link
Contributor

LinusU commented Dec 11, 2019

I have the same problem, and my setup is very similar. Just trying to print something in onBackgroundMesssage so that I can see it in logcat.

I can see the notification coming in and Android starting the app in logcat:

12-11 14:59:47.098  1926  1943 I ActivityManager: Start proc 18876:com.foo.myapp/u0a88 for broadcast com.foo.myapp/com.google.firebase.iid.FirebaseInstanceIdReceiver`

Here is my flutter doctor:

[✓] Flutter (Channel stable, v1.9.1+hotfix.6, on Mac OS X 10.15.1 19B88, locale en-SE)
    • Flutter version 1.9.1+hotfix.6 at /Users/linus/coding/flutter
    • Framework revision 68587a0916 (3 months ago), 2019-09-13 19:46:58 -0700
    • Engine revision b863200c37
    • Dart version 2.5.0

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.1)
    • Android SDK at /Users/linus/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.1
    • ANDROID_HOME = /Users/linus/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.2.1, Build version 11B500
    • CocoaPods version 1.8.4

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 42.0.1
    • Dart plugin version 191.8593
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[✓] VS Code (version 1.40.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.7.1

[✓] Connected device (1 available)
    • AOSP on IA Emulator • emulator-5554 • android-x86 • Android 9 (API 28) (emulator)

• No issues found!

@iapicca iapicca removed the blocked: customer-response Waiting for customer response, e.g. more information was requested. label Dec 12, 2019
@iapicca iapicca added the impact: crowd Affects many people, though not necessarily a specific customer with an assigned label. (P2) label Dec 27, 2019
@iapicca
Copy link

iapicca commented Dec 27, 2019

#125

@Eddydpyl
Copy link

Similar thing happening to me (#1709), but it my case, the method is called as long as I don't reopen my app once it has been installed. That is, once the app is installed and launched for the first time, if I go ahead and close it, onBackgroundMessage will be called when I send a data message. But if I reopen the app, and then close it once again, it will no longer be called.

@phodonou
Copy link

This might be an issue related to flutter_local_notification package:
MaikuB/flutter_local_notifications#111

@Eddydpyl
Copy link

Eddydpyl commented Dec 28, 2019

This might be an issue related to flutter_local_notification package:
MaikuB/flutter_local_notifications#111

Doesn't seem to be the case for me (I've checked just now). I have noticed something interesting though: The messages arrive just fine when the application is completely closed, but onBackgroundMessage won't trigger when the app is still running in the background. What I mentioned in #1709 applies to this new observation. I'll make myself a bit clearer:

  1. Launch the app for the first time, and move it to the background. Works as expected.
  2. Remove the app from the background. Still works as expected.
  3. Launch the app, and move it to the background. The callback no longer runs.
  4. Remove the app from the background. Works as expected.
  5. From this point onward, onBackgroundMessage will not be called when the app is running in the background, but it will continue to be called when it has been closed.

@Eddydpyl
Copy link

Eddydpyl commented Jan 7, 2020

I've made a pull request that solves the issue for me (#1774), can anyone else confirm?

@tigertore
Copy link

Yes, I can confirm that your change fixes the problem.
I have tested it several times and it works every time now.
My scenario:

  1. App is not running.
  2. We send a FCM data push message
  3. App starts up in background via onBackgroundMessage() and adds a notifcation to the status bar.
  4. User clicks notification and which starts the flutter app.
  5. User puts app in background
  6. We send a new FCM data push message

The message in point 6 was lost before your fix.
Now we receive it every time.

@cuijinfeng68
Copy link

Yes, I can confirm that your change fixes the problem.
I have tested it several times and it works every time now.
My scenario:

  1. App is not running.
  2. We send a FCM data push message
  3. App starts up in background via onBackgroundMessage() and adds a notifcation to the status bar.
  4. User clicks notification and which starts the flutter app.
  5. User puts app in background
  6. We send a new FCM data push message

The message in point 6 was lost before your fix.
Now we receive it every time.

How to use the last version?

@tigertore
Copy link

#First clone Eddy's repo:
git clone https://github.com/Eddydpyl/flutterfire.git

#Then point to this workspace, in pubspec.yaml:

dependencies:

firebase_messaging:
path: ../../../tmp/flutterfire/packages/firebase_messaging/

@Jackcui68
Copy link

#First clone Eddy's repo:
git clone https://github.com/Eddydpyl/flutterfire.git

#Then point to this workspace, in pubspec.yaml:

dependencies:

firebase_messaging:
path: ../../../tmp/flutterfire/packages/firebase_messaging/

I have tested it, onResume,On onLaunch is ok, but on background doesn't work.

[✓] Flutter (Channel stable, v1.12.13+hotfix.5, on Mac OS X 10.14.6 18G2022, locale zh-Hans-US)
• Flutter version 1.12.13+hotfix.5 at /Users/*****Desktop/flutter
• Framework revision 27321ebbad (4 weeks ago), 2019-12-10 18:15:01 -0800
• Engine revision 2994f7e1e6
• Dart version 2.7.0

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)

• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 28.0.3
• ANDROID_HOME = /Users/jackcui/Library/Android/sdk
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.3, Build version 11C29
• CocoaPods version 1.8.4

[✓] Android Studio (version 3.5)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 42.1.1
• Dart plugin version 191.8593
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[✓] Connected device (1 available)
• HUAWEI CAZ AL10 • XPUDU17302006263 • android-arm64 • Android 7.0 (API 24)

• No issues found!

@t0mHagen
Copy link

I've made a pull request that solves the issue for me (#1774), can anyone else confirm?

Awesome! I ran into exactly the same issue. Glad I came across your fix, much appreciated.

@Eddydpyl
Copy link

@Jackcui68 this is just a shot in the dark, but maybe the issue is with how your device handles background processes? Check out this website: https://dontkillmyapp.com/

@sebbyjp
Copy link

sebbyjp commented Jan 26, 2020

@Eddydpyl Does this solution only work for android or IOS as well...?

@Eddydpyl
Copy link

Eddydpyl commented Jan 27, 2020

@dazednconfusing it only fixes the issue in Android, and iOS can't process a data message when the app is not running, so it really isn't as useful. As far as I know, the onMessage callback is the one that should be triggered in iOS when receiving a data message, as long as the app is running. If it's not, the message should be queued to be received once the app is running.

@vov4ik08
Copy link

Hello. Any updates? for me call onBackgroundMessage does not work too. I am use for test real device with android 9

@braysonjohn148
Copy link

Hello. Any updates? for me call onBackgroundMessage does not work too. I am use for test real device with android 9

me too. if somebody gets something please

@vov4ik08
Copy link

Hello all. I realized what the problem is. For work onBackgroundMessage we must send notification only with param 'data' and without param notification. Php example code:

$push = new PushNotification('fcm');
   $push->setMessage([

        'data' => [
            'extraPayLoad1' => 'value1',
            'extraPayLoad2' => 'value2'
        ]
    ])

        ->setApiKey('apikey')
        ->setDevicesToken(['device token'])
        ->send();

This notification do not show but onBackgroundMessage will work. If you want show notification and run onBackgroundMessage you must send 2 notification from server, first as example above and second as

$push->setMessage([
        'notification' => [
            'title' => 'This is the title',
            'body' => 'This is the message',
            'sound' => 'default',
            'priority' => 'high',


        ],
       
    ])
     ->setApiKey('apikey')
        ->setDevicesToken(['device token'])
        ->send();

@braysonjohn148
Copy link

braysonjohn148 commented Mar 20, 2020

I tried data but still doesn't work, this is my index.js

exports.messageNotifications = functions.firestore.document('notification/{post}').onCreate(async (snapshot, context) => {

const posts = snapshot.data();
const payload = {
    notification: {
        title: 'New Order..!',
        body: `${posts.message} `,
        icon: 'notification_icon',
        click_action: 'FLUTTER_NOTIFICATION_CLICK' // required only for onResume or onLaunch callbacks
    },
    data: {
        title: `New message from ${postss.name} `,
        body: `${postss.message} `,
        icon: 'notification_icon',
        click_action: 'FLUTTER_NOTIFICATION_CLICK' // required only for onResume or onLaunch callbacks
    }
};

@vov4ik08
Copy link

notification: {
title: 'New Order..!',
body: ${posts.message} ,
icon: 'notification_icon',
click_action: 'FLUTTER_NOTIFICATION_CLICK' // required only for onResume or onLaunch callbacks
},

Try remove this
notification: {
title: 'New Order..!',
body: ${posts.message} ,
icon: 'notification_icon',
click_action: 'FLUTTER_NOTIFICATION_CLICK' // required only for onResume or onLaunch callbacks
},

@braysonjohn148
Copy link

But how will my notification be handled to the notification tray... for the user to get a notification. Please help

@vov4ik08
Copy link

But how will my notification be handled to the notification tray... for the user to get a notification. Please help

If you need work background and show notification, you must send 2 notification, first with

notification: {
title: 'New Order..!',
body: ${posts.message} ,
icon: 'notification_icon',
click_action: 'FLUTTER_NOTIFICATION_CLICK' // required only for onResume or onLaunch callbacks
},

and without data and second with data and without notification arrays

@a-chris
Copy link

a-chris commented Apr 13, 2020

Any news? I've tried with Notification message and Data Message but the onBackgroundMessage callback is not called when the app has been terminated

@Eddydpyl
Copy link

Eddydpyl commented Apr 13, 2020

@a-chris try my pull request (#1774). If your issue is with iOS, know that the behaviour is different than in Android: Data messages sent when the app is terminated will be received when the app is launched again, through the onMessage callback I believe.

@Salakar
Copy link
Member

Salakar commented May 12, 2020

@Eddydpyl thank you for PR #1774 - I've gone ahead and merged this and firebase_messaging version 6.0.15 has been published.

Will go ahead and close this issue now - thanks.

@Salakar Salakar closed this as completed May 12, 2020
@firebase firebase locked and limited conversation to collaborators Aug 6, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
impact: crowd Affects many people, though not necessarily a specific customer with an assigned label. (P2) plugin: messaging type: bug Something isn't working
Projects
None yet
Development

No branches or pull requests