Flutterfire: [firebase_messaging] PluginRegistrantCallback is not set on Android

Created on 27 Feb 2020  Â·  66Comments  Â·  Source: FirebaseExtended/flutterfire

Fatal Exception: java.lang.RuntimeException
Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: 
java.lang.RuntimeException: PluginRegistrantCallback is not set.

This is caused by:

Caused by java.lang.RuntimeException: PluginRegistrantCallback is not set.
       at io.flutter.plugins.firebasemessaging.
FlutterFirebaseMessagingService.executeDartCallbackInBackgroundIsolate(FlutterFirebaseMessagingService.java)
       at io.flutter.plugins.firebasemessaging.
FlutterFirebaseMessagingService.onCreate(FlutterFirebaseMessagingService.java)

This happens on Android when running a Flutter app built with firebase_messaging: 6.0.9 and Flutter 1.15.4-pre.199.


This also happens every time calling FirebaseMessaging.configure in the Flutter app when running on Android:

PlatformException(error, PluginRegistrantCallback is not set., null)
  StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
  MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
<asynchronous suspension>
  MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
  FirebaseMessaging.configure (package:firebase_messaging/firebase_messaging.dart:130:16)
crowd android messaging bug

Most helpful comment

@bretie, Kotlin worked for me. The procedure is the following:

  1. Improve android/app/build.gradle file:
// At the bottom of the file, you will find a `dependencies` section

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Required for firebase messaging
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
}
  1. Create an Application class
package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}
  1. In AndroidManifest.xml improve the application tag:
<!-- FROM -->
<application android:name="io.flutter.app.FlutterApplication" ... />

<!-- TO -->
<application android:name=".Application" ... />
  1. In the dart code make sure the onBackgroundMessage callback is static or out of class function.
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('On background message $message');
  return Future<void>.value();
}

class _WhateverState extends State<Whatever> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onBackgroundMessage: _onBackgroundMessage,
      // ...
    );
  }
}

All 66 comments

exact same issue. the error appears when using background notification.

`E/MethodChannel#plugins.flutter.io/firebase_messaging(12720): Failed to handle method call
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720): java.lang.RuntimeException: PluginRegistrantCallback is not set.
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:157)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.onMethodCall(FirebaseMessagingPlugin.java:176)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:231)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:93)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:642)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at android.os.MessageQueue.next(MessageQueue.java:326)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at android.os.Looper.loop(Looper.java:160)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at android.app.ActivityThread.main(ActivityThread.java:6669)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/MethodChannel#plugins.flutter.io/firebase_messaging(12720):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

I/mattuvandi.use(12720): Background concurrent copying GC freed 18711(1011KB) AllocSpace objects, 12(304KB) LOS objects, 50% free, 2MB/4MB, paused 11.526ms total 155.904ms

E/flutter (12720): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, PluginRegistrantCallback is not set., null)
E/flutter (12720): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (12720): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33)
E/flutter (12720): <asynchronous suspension>
E/flutter (12720): #2      FirebaseMessaging.configure (package:firebase_messaging/firebase_messaging.dart:130:16)
E/flutter (12720): #3      firebaseNotification (package:Mattuvandi/app_screens/home/Home.dart:432:27)
E/flutter (12720): #4      _HomeState.build (package:Mattuvandi/app_screens/home/Home.dart:48:7)
E/flutter (12720): #5      StatefulElement.build (package:flutter/src/widgets/framework.dart:4334:27)
E/flutter (12720): #6      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4223:15)
E/flutter (12720): #7      Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
E/flutter (12720): #8      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
E/flutter (12720): #9      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11)
E/flutter (12720): #10     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
E/flutter (12720): #11     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (12720): #12     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (12720): #13     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14)
E/flutter (12720): #14     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (12720): #15     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (12720): #16     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
E/flutter (12720): #17     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
E/flutter (12720): #18     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
E/flutter (12720): #19     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
E/flutter (12720): #20     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (12720): #21     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (12720): #22     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14)
E/flutter (12720): #23     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (12720): #24     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (12720): #25     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14)
E/flutter (12720): #26     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (12720): #27     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (12720): #28     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
E/flutter (12720): #29     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
E/flutter (12720): #30     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
E/flutter (12720): #31     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11)
E/flutter (12720): #32     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
E/flutter (12720): #33     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (12720): #34     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (12720): #35     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14)
E/flutter (12720): #36     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (12720): #37     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (12720): #38     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14)
E/flutter (12720): #39     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
E/flutter (12720): #40     Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
E/flutter (12720): #41     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16)
E/flutter (12720): #42     Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
E/flutter (12720): #43     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
E/flutter (12720): #44     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11)
E/flutter (12720): #45     Com`

same issue, is there any solution yet?

Application.java replace:

public class Application extends FlutterApplication implements PluginRegistrantCallback {
  @Override
  public void onCreate() {
    super.onCreate();
    FlutterFirebaseMessagingService.setPluginRegistrant(this);
  }

  @Override
  public void registerWith(PluginRegistry registry) {
    GeneratedPluginRegistrant.registerWith(registry);
  }
}

Application.java with:

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;

public class Application extends FlutterApplication implements PluginRegistrantCallback {

    @Override
    @CallSuper
    public void onCreate() {
        super.onCreate();
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    @Override
    public void registerWith(PluginRegistry pluginRegistry) {
        FirebaseMessagingPlugin.registerWith(pluginRegistry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
    }
}

I run in to error while using _@callsuper_. As per android document it is deprecated.
with your suggested code i get same error.

manifest.xml:


` package="com.mattuvandi.user">

<!-- io.flutter.app.FlutterApplication is an android.app.Application that
     calls FlutterMain.startInitialization(this); in its onCreate method.
     In most cases you can leave this as-is, but you if you want to provide
     additional functionality it is fine to subclass or reimplement
     FlutterApplication and put your custom class here. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />       
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<application
    android:name="io.flutter.app.FlutterApplication"
    android:label="Mattuvandi"
    android:icon="@mipmap/ic_launcher">

     <meta-data android:name="com.google.android.geo.API_KEY"
           android:value="*************************************"/>               
    <activity
        android:name=".MainActivity"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
        <!-- This keeps the window background of the activity showing
             until Flutter renders its first frame. It can be removed if
             there is no splash screen (such as the default splash screen
             defined in @style/LaunchTheme). -->
        <meta-data
            android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
            android:value="true" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
          <intent-filter>
            <action android:name="FLUTTER_NOTIFICATION_CLICK" />
            <category android:name="android.intent.category.DEFAULT" />
          </intent-filter>
    </activity>    
     <activity android:name=".Application"
              android:launchMode="singleTop"
              android:theme="@android:style/Theme.Black.NoTitleBar"
              android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
              android:hardwareAccelerated="true"
              android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>     
</application>

`


Mainactivity.Java

````package com.mattuvandi.user;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this); //auto generated?
}
}
````

Application.java


````
package com.mattuvandi.user;
import android.os.Bundle;
import io.flutter.app.FlutterApplication;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;

public class Application extends FlutterApplication implements PluginRegistrantCallback {
@Override
// @CallSuper
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}

@Override
public void registerWith(PluginRegistry pluginRegistry) {
FirebaseMessagingPlugin.registerWith(pluginRegistry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
}````

Error:


E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): Failed to handle method call E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): java.lang.RuntimeException: PluginRegistrantCallback is not set. E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:157) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.onMethodCall(FirebaseMessagingPlugin.java:176) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:231) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:93) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:642) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at android.os.MessageQueue.nativePollOnce(Native Method) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at android.os.MessageQueue.next(MessageQueue.java:326) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at android.os.Looper.loop(Looper.java:160) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at android.app.ActivityThread.main(ActivityThread.java:6669) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at java.lang.reflect.Method.invoke(Native Method) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) E/MethodChannel#plugins.flutter.io/firebase_messaging(14771): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) I/flutter (14771): Login Status true I/mattuvandi.use(14771): Background concurrent copying GC freed 12428(1431KB) AllocSpace objects, 23(684KB) LOS objects, 49% free, 2024KB/3MB, paused 1.106ms total 237.579ms E/flutter (14771): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, PluginRegistrantCallback is not set., null) E/flutter (14771): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7) E/flutter (14771): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33) E/flutter (14771): <asynchronous suspension> E/flutter (14771): #2 FirebaseMessaging.configure (package:firebase_messaging/firebase_messaging.dart:130:16) E/flutter (14771): #3 firebaseNotification (package:Mattuvandi/app_screens/home/Home.dart:432:27) E/flutter (14771): #4 _HomeState.build (package:Mattuvandi/app_screens/home/Home.dart:48:7) E/flutter (14771): #5 StatefulElement.build (package:flutter/src/widgets/framework.dart:4334:27) E/flutter (14771): #6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4223:15) E/flutter (14771): #7 Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5) E/flutter (14771): #8 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5) E/flutter (14771): #9 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11) E/flutter (14771): #10 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5) E/flutter (14771): #11 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter (14771): #12 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/flutter (14771): #13 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14) E/flutter (14771): #14 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter (14771): #15 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/flutter (14771): #16 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16) E/flutter (14771): #17 Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5) E/flutter (14771): #18 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5) E/flutter (14771): #19 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5) E/flutter (14771): #20 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter (14771): #21 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/flutter (14771): #22 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14) E/flutter (14771): #23 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter (14771): #24 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/flutter (14771): #25 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14) E/flutter (14771): #26 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter (14771): #27 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/flutter (14771): #28 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16) E/flutter (14771): #29 Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5) E/flutter (14771): #30 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5) E/flutter (14771): #31 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11) E/flutter (14771): #32 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5) E/flutter (14771): #33 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter (14771): #34 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/flutter (14771): #35 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14) E/flutter (14771): #36 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter (14771): #37 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/flutter (14771): #38 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5445:14) E/flutter (14771): #39 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14) E/flutter (14771): #40 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12) E/flutter (14771): #41 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4243:16) E/flutter (14771): #42 Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5) E/flutter (14771): #43 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5) E/flutter (14771): #44 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4381:11)

@ClevercodeTech @h0x539 Could you maybe wrap your code into a <details> </details> to make this thread more readable?

@ClevercodeTech @h0x539 Could you maybe wrap your code into a <details> </details> to make this thread more readable?

thanks for the suggestion. Updated as per your suggestion.

@ClevercodeTech

Try to make a standalone build of the android module.

Android Studio -> right click on android package -> Flutter -> Open Android module in Android Studio

Flutter Android module in Android Studio -> Terminal -> ./gradlew clean && ./gradlew build

Resolved the issue. Flutter instruction was not clear or i didn't get what they were saying.
i changed the following line in the beginning of my manifest.xml:

android:name="io.flutter.app.FlutterApplication"

to

android:name=".Application"

android:name="io.flutter.app.FlutterApplication"
**android:name=".Application"**
android:label="Mattuvandi"
android:icon="@mipmap/ic_launcher">
android:value="*************************************"/>
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />









android:launchMode="singleTop"
android:theme="@android:style/Theme.Black.NoTitleBar" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">





I did it and the error is out, but it is not calling the onBackgroundMessage anymore.

Closing this issue because it looks like it's resolved.

@kalibu if you are still experiencing issues calling the onBackgroundMessage with the latest version of Flutter and FlutterFire plugin, can you please provide your updated flutter doctor -v
and your flutter run --verbose/flutter build --verbose ?
Also, to better address the issue, would be helpful
if you could post a self contained app on github
or the steps to reproduce it.
Thank you

@helenaford

This has not been resolved at all.
Hint: there has not been an update to the plugin (on Android) since I opened this issue. I only replaced one deprecated method that had nothing to do with this, so basically there has not been an update since I opened the issue..

@creativecreatorormaybenot did you try the solution provided by @ClevercodeTech ?

@helenaford That "solution" only makes the error message go away and does not fix the underlying problem (the plugin is broken on Android, see #2017 for a start; there are way more issues for background messages).

The plugin would at least need to address this somewhere. Even if the underlying problem is not fixed immediately, the README section and more would need to be updated.

@helenaford That "solution" only makes the error message go away and does not fix the underlying problem (the plugin is broken on Android, see #2017 for a start; there are way more issues for background messages).

The plugin would at least need to address this _somewhere_. Even if the underlying problem is not fixed immediately, the README section and more would need to be updated.

Background message works for me.

you need to add a static method to capture the incoming message from firebase server. Below is a sample code

static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async { print(message); return Future<void>.value(); }

below is the detailed code

```
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/material.dart';
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

class FirebaseClass {

firebaseNotification(context,topic ) {
var platform = Theme.of(context).platform;
final requestServer = RequestServer();
print("firebaseinitiated");
_firebaseMessaging.subscribeToTopic(topic);
_firebaseMessaging.configure(
onMessage: (Map message) async {
print("onMessage: $message");
},
onBackgroundMessage: platform == TargetPlatform.iOS ? null : myBackgroundMessageHandler,
onLaunch: (Map message) async {
print("onLaunch: $message");
},
onResume: (Map message) async {
print("onResume: $message");
},
);
if (platform == TargetPlatform.iOS) {
_firebaseMessaging
.requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
}
_firebaseMessaging.getToken().then((String token) {
assert(token != null);
//setting fire base toke in own server this is needed to message from your server
// requestServer is a custom class to connect with my server
requestServer.requestServer("SetFirebaseToken", context).then((e) {
e == 1 ? print("Push Messaging token: $token") : print("errror sending data to server");
});
});

}

notification() async {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = new AndroidInitializationSettings('logo');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(
initializationSettings,
);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(0, 'plain title', 'plain body', platformChannelSpecifics,
payload: 'item x');
}

static Future myBackgroundMessageHandler(Map message) async {
print(message);
return Future.value();
}

}
```

@ClevercodeTech

If that works with all versions (Flutter beta + master too), then I suppose that would be a solution.
Still, the issue should remain open until this is at least integrated into the README.

@ClevercodeTech Can you provide detailed instructions?

@ClevercodeTech Can you provide detailed instructions?

Please follow the instruction as shown in the following link
https://pub.dev/packages/firebase_messaging

for receiving background message.
importantly you need to change your android manifest.

usually flutter application starts like this

<application
    android:name="io.flutter.app.FlutterApplication"

you need to change the name to below

<application android:name=".Application" ...>

.Application refers to Application.java. Which contains below.
package com.mattuvandi.user is my application. This should be changed to yours. e.g

package com.domain.application

package com.mattuvandi.user; 
import android.os.Bundle; 
import io.flutter.app.FlutterApplication; 
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;

public class Application extends FlutterApplication implements PluginRegistrantCallback {
@override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}

@override
public void registerWith(PluginRegistry pluginRegistry) {
FirebaseMessagingPlugin.registerWith(pluginRegistry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
}

Doesn't work for me. Tried to switch branch from stable to master, didn't help.

Doesn't work for me. Tried to switch branch from stable to master, didn't help.

could you please post your code.

Sure.

// Application.kt

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
        // ...
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
        // ...
    }
}
// AndroidManifest.xml

<application
    android:name=".Application" // Changed from `io.flutter.app.FlutterApplication`
    ... />
// build.gradle under app

// ...

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation 'com.google.firebase:firebase-messaging:20.1.6'

    // ...
}

have you included

// under [project]/android/app/build.gradle
apply plugin: 'com.google.gms.google-services'

Yes.

// under [project]/android/build.gradle
buildscript {
    ext.kotlin_version = '1.3.72'

    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.3'
        classpath 'com.google.gms:google-services:4.3.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
// under [project]/android/app/build.gradle
// ...
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

@lexdevel

Not sure if this helps. But i added activity tag as below in manifest.

<activity android:name=".Application"
   android:launchMode="singleTop"
   android:theme="@android:style/Theme.Black.NoTitleBar"
          android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
   android:hardwareAccelerated="true"
   android:windowSoftInputMode="adjustResize">
   <intent-filter>
       <action android:name="android.intent.action.MAIN"/>
       <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
   <intent-filter>
       <action android:name="FLUTTER_NOTIFICATION_CLICK" />
       <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
</activity>   

@ClevercodeTech, thanks, unfortunately I have pretty similar config.

@lexdevel
please post your error.

@ClevercodeTech, sure, you may find output below. Reproduced when I specify onBackgroundMessage callback in the configure method of the FirebaseMessaging class.

E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): Failed to handle method call
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004): java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.app.Activity.getMainLooper()' on a null object reference
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at com.google.android.gms.common.api.GoogleApi.<init>(Unknown Source:50)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at com.google.android.gms.location.FusedLocationProviderClient.<init>(Unknown Source:8)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at com.google.android.gms.location.LocationServices.getFusedLocationProviderClient(Unknown Source:2)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at com.lyokone.location.FlutterLocation.setActivity(FlutterLocation.java:106)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at com.lyokone.location.LocationPlugin.registerWith(LocationPlugin.java:35)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:164)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.onMethodCall(FirebaseMessagingPlugin.java:176)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at android.os.MessageQueue.next(MessageQueue.java:336)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at android.os.Looper.loop(Looper.java:174)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at android.app.ActivityThread.main(ActivityThread.java:7356)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/MethodChannel#plugins.flutter.io/firebase_messaging( 5004):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
E/flutter ( 5004): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'android.os.Looper android.app.Activity.getMainLooper()' on a null object reference, null)
E/flutter ( 5004): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter ( 5004): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter ( 5004): <asynchronous suspension>
E/flutter ( 5004): #2      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
E/flutter ( 5004): #3      FirebaseMessaging.configure (package:firebase_messaging/firebase_messaging.dart:130:16)
E/flutter ( 5004): #7      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4644:58)
E/flutter ( 5004): #8      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4480:5)
E/flutter ( 5004): #9      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #10     Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #11     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #12     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #13     Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #14     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4531:16)
E/flutter ( 5004): #15     Element.rebuild (package:flutter/src/widgets/framework.dart:4222:5)
E/flutter ( 5004): #16     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4485:5)
E/flutter ( 5004): #17     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4480:5)
E/flutter ( 5004): #18     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #19     Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #20     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #21     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #22     Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #23     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #24     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #25     Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #26     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4531:16)
E/flutter ( 5004): #27     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4679:11)
E/flutter ( 5004): #28     Element.rebuild (package:flutter/src/widgets/framework.dart:4222:5)
E/flutter ( 5004): #29     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4485:5)
E/flutter ( 5004): #30     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4670:11)
E/flutter ( 5004): #31     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4480:5)
E/flutter ( 5004): #32     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #33     Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #34     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #35     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #36     Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #37     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5834:14)
E/flutter ( 5004): #38     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3450:14)
E/flutter ( 5004): #39     Element.updateChild (package:flutter/src/widgets/framework.dart:3218:18)
E/flutter ( 5004): #40     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4531:16)
E/flutter ( 5004): #41     StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4679:11)
E/flutter ( 5004): #42     Element.rebuild (package:flutter/src/widgets/framework.dart:4222:5)
E/flutter ( 5004): #43     ComponentElement._firstBuild (package:flutter/src/widgets/fra
E/flutter ( 5004): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method FcmDartService#initialized on channel plugins.flutter.io/firebase_messaging_background)
E/flutter ( 5004): #0      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:154:7)
E/flutter ( 5004): <asynchronous suspension>
E/flutter ( 5004): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
E/flutter ( 5004): #2      _fcmSetupBackgroundChannel (package:firebase_messaging/firebase_messaging.dart:50:21)
E/flutter ( 5004): #3      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:257:25)
E/flutter ( 5004): #4      _rootRun (dart:async/zone.dart:1184:13)
E/flutter ( 5004): #5      _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter ( 5004): #6      _runZoned (dart:async/zone.dart:1619:10)
E/flutter ( 5004): #7      runZonedGuarded (dart:async/zone.dart:1608:12)
E/flutter ( 5004): #8      _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:249:5)
E/flutter ( 5004): #9      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
E/flutter ( 5004): #10     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

E/flutter ( 5004): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method FcmDartService#initialized on channel plugins.flutter.io/firebase_messaging_background)

i believe it may be due to your background message handler.

Below is my firebase class which handles background notification.
Note background message handler is outside the class.


import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

class FirebaseClass {
  firebaseNotification(context, userInfo) {
    var platform = Theme.of(context).platform;
    _firebaseMessaging.subscribeToTopic(userID); //subscribe to 

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        notification(message)
         print("onMessage: $message"); //call Local notification here or any code you wish
      },
      onBackgroundMessage: platform == TargetPlatform.iOS ? null : myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        notification(message)
        print("onLaunch: $message"); //call Local notification here or any code you wish
      },
      onResume: (Map<String, dynamic> message) async {
        notification(message)
       print("onResume: $message"); //call Local notification here or any code you wish
      },
    );
    if (platform == TargetPlatform.iOS) {
      _firebaseMessaging
          .requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true));
      _firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
        print("Settings registered: $settings");
      });
    }

    _firebaseMessaging.getToken().then((String token) {
      assert(token != null);
        // here send the token to server

    });
  }


  static notification(message) async {   
    var title = message["notification"]["title"];
    var body = message["notification"]["body"];

    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    var initializationSettingsAndroid = new AndroidInitializationSettings('launcher_icon');
    var initializationSettingsIOS = new IOSInitializationSettings();

    var initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
    flutterLocalNotificationsPlugin.initialize(
      initializationSettings, //onSelectNotification: onSelectNotification
    );

    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'your channel id', 'your channel name', 'your channel description',
        importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(0, title, body, platformChannelSpecifics, payload: 'item x');
  }


}


   Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
    FirebaseClass.notification(message);
    return Future<void>.value();
  }

I moved the FirebaseMessaging class instance and a background callback outside of the widget (like in the example you provided me with), still have an issue. Before, I followed the docs: created a static function to handle the background message.

@lexdevel make sure the name matches.

firebase config
onBackgroundMessage: platform == TargetPlatform.iOS ? null : myBackgroundMessageHandler,

   Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
    FirebaseClass.notification(message);
    return Future<void>.value();
  }

make sure _myBackgroundMessageHandler_ is standalone not inside any class.

e.g

imports //necessary imports
class stateful widget {
//widget class
}
myBackgroundMessageHandler

Yes, double checked.

import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

class DemoPage extends StatefulWidget {
  @override
  _DemoPageState createState() => _DemoPageState();
}

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('I was here!');
  return Future<void>.value();
}

class _DemoPageState extends State<DemoPage> {
  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onMessage: (_) => null,
      onLaunch: (_) => null,
      onResume: (_) => null,
      onBackgroundMessage: _onBackgroundMessage
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

I would more expect problem on native part, seems the is an error trying to register a plugin.

i didn't initiate the firebase configuration from initState().
see below my implementation. I call my firebase class from widgets. Not sure if it helps you. you can try.

  bool runfirebase = true;
@override
  Widget build(BuildContext context) {
    final UserInfo userInfo = Provider.of<UserInfo>(context);  
      if (runfirebase) {
      firebaseClass.firebaseNotification(context);
        runfirebase = false;
    }
}

That's a bit strange, to be honest, I support we should use the build method for building widgets. However, I just tried and this didn't help.
@ClevercodeTech, I would really appreciate it if you could provide me with the versions of flutter, firebase messaging plugin and com.google.gms:google-services. I hope I could downgrade them to make the background messages work.

I hope you included google-services.json in /android/app folder.
also internet permission in mnifest.xml

Flutter Flutter 1.12.13+hotfix.9
dependencies:
firebase_messaging: ^6.0.13

/android/build.gradle

 dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.2'
    }

/android/App/build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'

dependencies {
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'  
}

Thank you. Unfortunately had the same result. Regarding the json file, of course I did include it. I face the issue only for background messaging, other work fine.

@lexdevel

Not sure if this helps. But i added activity tag as below in manifest.

<activity android:name=".Application"
   android:launchMode="singleTop"
   android:theme="@android:style/Theme.Black.NoTitleBar"
          android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection"
   android:hardwareAccelerated="true"
   android:windowSoftInputMode="adjustResize">
   <intent-filter>
       <action android:name="android.intent.action.MAIN"/>
       <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
   <intent-filter>
       <action android:name="FLUTTER_NOTIFICATION_CLICK" />
       <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
</activity>   

@ClevercodeTech

I followed your example code but couldn't get the background message working when the app is slide away from the phone tray.

Firstly, I'm curious to ask if your app received background messages when it's not on the phone tray?

And secondly, I noticed the quoted reply has ".Application" as it's activity name. Does this mean I should use this in both the <application> and<activity> level?

Thanks.

@ClevercodeTech I think I found an issue: I had several plugins initialization and seems there's a conflict with Location plugin.

override fun registerWith(registry: PluginRegistry?) {
    LocationPlugin.registerWith(registry?.registrarFor("com.lyokone.location.LocationPlugin")) // Comment this line to resolve the issue
    FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    SharedPreferencesPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin"))
}

Regarding the Location, it's not necessary to call the registerWith method for the plugin, but in my case it was required, since I used Location in background (I came up with this solution and that helped me).

Anyway, thanks. I can confirm that I got rid of the issue.

But calling FirebaseMessagingPlugin.registerWith() really only is a workaround and not a solution.

With android embedding v2 registerWith() should not be needed anymore and is only kept as a fallback for old flutter applications.

Ideally FirebaseMessaging should be setup correctly within onAttachedToEngine() .. so that it would automatically be able to run in the background. Thats basically what android v2 embedding is all about.. That you DON'T have to write all these things anymore to make stuff like that possible.

@lazylazyllama, I understand, but the plugin DOES NOT work correctly, so as other plugins I checked. So for now I have to call registerWith method.

@ClevercodeTech changing

from

android:name="io.flutter.app.FlutterApplication"

to

android:name=".Application"

to resolved my issue

The POINT is:
if:
android:name="xxx.xxx.xxx.YourApplication"
then you need to put FlutterFirebaseMessagingService.setPluginRegistrant(this);
to xxx.xxx.xxx.YourApplication's onCreate
and

override fun registerWith(registry: PluginRegistry?) same.

@ClevercodeTech I think I found an issue: I had several plugins initialization and seems there's a conflict with Location plugin.

override fun registerWith(registry: PluginRegistry?) {
    LocationPlugin.registerWith(registry?.registrarFor("com.lyokone.location.LocationPlugin")) // Comment this line to resolve the issue
    FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    SharedPreferencesPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin"))
}

Regarding the Location, it's not necessary to call the registerWith method for the plugin, but in my case it was required, since I used Location in background (I came up with this solution and that helped me).

Anyway, thanks. I can confirm that I got rid of the issue.

Can you please, for the love of all Flutter and the buggyness of this issue.

Please post your implementation. There is not enough success with Kotlin trying to use this package.

@bretie

If you are using multiple plugin use the following implementation
in your MainActivity java


package com.yourdomain.appname; // change it appropriately
import android.os.Bundle;

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {

 @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    }

    @Override
    public void configureFlutterEngine(@NonNull final FlutterEngine flutterEngine) {
 GeneratedPluginRegistrant.registerWith(flutterEngine);      
}

}

Application.java


package com.yourdomain.appname; // change it appropriately
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
  @Override
  public void onCreate() {
    super.onCreate();
    FlutterFirebaseMessagingService.setPluginRegistrant(this);
  }

  @Override
  public void registerWith(PluginRegistry registry) {
    FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
  }
}

manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package=" com.yourdomain.appname">  
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <application
        android:name=".Application"

Hope it solves your issue.

@bretie

If you are using multiple plugin use the following implementation
in your MainActivity java


package com.yourdomain.appname; // change it appropriately
import android.os.Bundle;

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {

 @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    }

    @Override
    public void configureFlutterEngine(@NonNull final FlutterEngine flutterEngine) {
 GeneratedPluginRegistrant.registerWith(flutterEngine);      
}

}

Application.java


package com.yourdomain.appname; // change it appropriately
import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
  @Override
  public void onCreate() {
    super.onCreate();
    FlutterFirebaseMessagingService.setPluginRegistrant(this);
  }

  @Override
  public void registerWith(PluginRegistry registry) {
    FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
  }
}

manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package=" com.yourdomain.appname">  
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <application
        android:name=".Application"

Hope it solves your issue.

I need it in Kotlin, I'm not using Java for my android app. Is there any way to port this over?

@bretie

My suggestion don’t spend so much time solving a problem in same way. Try trial and error.

Anyways,

You have two options.

One: if you don’t have any other codes in kotlin. Just use this implementation it should work.

Two: use IntelliJ in android studio to convert this to kotlin.

@bretie, Kotlin worked for me. The procedure is the following:

  1. Improve android/app/build.gradle file:
// At the bottom of the file, you will find a `dependencies` section

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Required for firebase messaging
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
}
  1. Create an Application class
package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}
  1. In AndroidManifest.xml improve the application tag:
<!-- FROM -->
<application android:name="io.flutter.app.FlutterApplication" ... />

<!-- TO -->
<application android:name=".Application" ... />
  1. In the dart code make sure the onBackgroundMessage callback is static or out of class function.
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('On background message $message');
  return Future<void>.value();
}

class _WhateverState extends State<Whatever> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onBackgroundMessage: _onBackgroundMessage,
      // ...
    );
  }
}

@bretie, also I got rid of the Location plugin and switched to the Geolocator plugin. That worked fine.

In my case the problem was caused by KeyboardVisibility plugin. Removing it has solved it.

In my case the problem was caused by KeyboardVisibility plugin. Removing it has solved it.

You gave me the solution:
Removing the flutter_keyboard_visibility worked for me.

import android.os.Bundle;

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public void configureFlutterEngine(@NonNull final FlutterEngine flutterEngine) {

GeneratedPluginRegistrant.registerWith(flutterEngine);
}

}

Helllo.
Thanks for helping.

I tried everything
It`s all red here.

RED -> import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
RED -> import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;

RED -> FlutterFirebaseMessagingService.setPluginRegistrant(this);

@bretie, Kotlin worked for me. The procedure is the following:

  1. Improve android/app/build.gradle file:
// At the bottom of the file, you will find a `dependencies` section

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Required for firebase messaging
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
}
  1. Create an Application class
package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}
  1. In AndroidManifest.xml improve the application tag:
<!-- FROM -->
<application android:name="io.flutter.app.FlutterApplication" ... />

<!-- TO -->
<application android:name=".Application" ... />
  1. In the dart code make sure the onBackgroundMessage callback is static or out of class function.
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('On background message $message');
  return Future<void>.value();
}

class _WhateverState extends State<Whatever> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onBackgroundMessage: _onBackgroundMessage,
      // ...
    );
  }
}

Thanks so much you save my life

@bretie, Kotlin worked for me. The procedure is the following:

  1. Improve android/app/build.gradle file:
// At the bottom of the file, you will find a `dependencies` section

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Required for firebase messaging
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
}
  1. Create an Application class
package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}
  1. In AndroidManifest.xml improve the application tag:
<!-- FROM -->
<application android:name="io.flutter.app.FlutterApplication" ... />

<!-- TO -->
<application android:name=".Application" ... />
  1. In the dart code make sure the onBackgroundMessage callback is static or out of class function.
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('On background message $message');
  return Future<void>.value();
}

class _WhateverState extends State<Whatever> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onBackgroundMessage: _onBackgroundMessage,
      // ...
    );
  }
}

Thanks so much you save my life

in what dir do i place Application.java ?

@bretie, Kotlin worked for me. The procedure is the following:

  1. Improve android/app/build.gradle file:
// At the bottom of the file, you will find a `dependencies` section

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Required for firebase messaging
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
}
  1. Create an Application class
package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}
  1. In AndroidManifest.xml improve the application tag:
<!-- FROM -->
<application android:name="io.flutter.app.FlutterApplication" ... />

<!-- TO -->
<application android:name=".Application" ... />
  1. In the dart code make sure the onBackgroundMessage callback is static or out of class function.
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('On background message $message');
  return Future<void>.value();
}

class _WhateverState extends State<Whatever> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onBackgroundMessage: _onBackgroundMessage,
      // ...
    );
  }
}

Thanks so much you save my life

Thank you.
I will try this.

But in my app I have to go to other Activity, how can I go to other screen if we don't have context at Top-Level function?

Please, help! S2

I am getting this error while calling firebaseMessaging.configure(); function...
Never seen this before, but then one day it suddenly appears every time on open app...

E/AndroidRuntime(29447): java.lang.RuntimeException: Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference E/AndroidRuntime(29447): at android.app.ActivityThread.handleCreateService(ActivityThread.java:3571) E/AndroidRuntime(29447): at android.app.ActivityThread.access$1300(ActivityThread.java:202) E/AndroidRuntime(29447): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1681) E/AndroidRuntime(29447): at android.os.Handler.dispatchMessage(Handler.java:107) E/AndroidRuntime(29447): at android.os.Looper.loop(Looper.java:198) E/AndroidRuntime(29447): at android.app.ActivityThread.main(ActivityThread.java:6729) E/AndroidRuntime(29447): at java.lang.reflect.Method.invoke(Native Method) E/AndroidRuntime(29447): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) E/AndroidRuntime(29447): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)

@SpinnerOfYarns, it seems the plugin wasn't registered. Did you create an Application class?

package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}

So I followed all the steps to implement it with Kotlin I created the Application class because it was missing – still no way to get the onBackground to work properly.

When I send a test message I receive it on both Android and iOS. On iOS it works fine both app running and terminated. On Android foreground works fine, but when on background or terminated the notification appears in the system tray and when I tap it the app starts, but the message is empty.

I've tried to debug the issue using Logcat, but there are nothing suspicious. When the phone receive the notification (with app terminated) in the system tray the Log says "Starting download of the .png" and no more clues about what happens. The print of the function I use to handle the background message doesn't appear at all. Here the function:

Future<dynamic> onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('On background message $message');
  print('On background message $message');
  stderr.writeln('stderr.writeln $message');
  log('On background log $message');
  stdout.writeln('OOKKKOKOKOKOK OKO OK OK OK OK OK OKO KOK OK');
  return Future<void>.value();
}

When I tap the notification, the app starts, the _onResume_ triggers and I receive this message:

google.sent_time: number, click_action: FLUTTER_NOTIFICATION_CLICK, google.original_priority: high, collapse_key: app_name_here, google.delivered_priority: high, from: number, google.message_id: 0:1597765388628367%42e897xc324e35dc4e42e8974e, google.ttl: number

Any idea how to debug this?

Buff, I've started reading the documentation again. I followed the link that says refer to the "Firebase Documentation about FCM for all the details..."
So there was a detail I've missed that says:

"Add the following to your app's manifest" :

 <service
            android:name=".kotlin.MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
</service>

I've added it and the code started complaining about the missing MyFirebaseMessagingService class. I looked onto the Kotlin folder, didn't see it so created one using this example https://github.com/firebase/quickstart-android/blob/f2676749632938d536741f2c5b6d668dfea7c4c7/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/kotlin/MyFirebaseMessagingService.kt
and then the code started complaining about unresolved references so this is the point I give up on this at the moment. I wonder why my Kotlin folder were empty and I had to create the Application class manually? And then this MyFirebaseMessagingService.kt? It feels like something is very wrong with the documentation or the plugin itself.

Also my Application class is all red complaining about:
"Cannot access 'android.app.Application' which is a supertype of 'my.app.name.Application'. Check your module classpath for missing or conflicting dependencies
Cannot access 'java.lang.Object' which is a supertype of 'my.app.name.Application'. Check your module classpath for missing or conflicting dependencies"
Cannot access 'android.app.Application' which is a supertype of 'my.app.name.Application'. Check your module classpath for missing or conflicting dependencies
Cannot access 'java.lang.Object' which is a supertype of 'my.app.name.Application'. Check your module classpath for missing or conflicting dependencies
Unresolved reference: FlutterFirebaseMessagingService

@bretie, Kotlin worked for me. The procedure is the following:

  1. Improve android/app/build.gradle file:
// At the bottom of the file, you will find a `dependencies` section

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Required for firebase messaging
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
}
  1. Create an Application class
package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}
  1. In AndroidManifest.xml improve the application tag:
<!-- FROM -->
<application android:name="io.flutter.app.FlutterApplication" ... />

<!-- TO -->
<application android:name=".Application" ... />
  1. In the dart code make sure the onBackgroundMessage callback is static or out of class function.
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('On background message $message');
  return Future<void>.value();
}

class _WhateverState extends State<Whatever> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onBackgroundMessage: _onBackgroundMessage,
      // ...
    );
  }
}

This worked for me, thanks! 😊

@bretie, Kotlin worked for me. The procedure is the following:

  1. Improve android/app/build.gradle file:
// At the bottom of the file, you will find a `dependencies` section

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Required for firebase messaging
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
}
  1. Create an Application class
package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}
  1. In AndroidManifest.xml improve the application tag:
<!-- FROM -->
<application android:name="io.flutter.app.FlutterApplication" ... />

<!-- TO -->
<application android:name=".Application" ... />
  1. In the dart code make sure the onBackgroundMessage callback is static or out of class function.
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('On background message $message');
  return Future<void>.value();
}

class _WhateverState extends State<Whatever> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onBackgroundMessage: _onBackgroundMessage,
      // ...
    );
  }
}

Thanks @lexdevel. This solution worked for Android on Flutter 1.20.2 with these package versions:
firebase_core: ^0.5.0
firebase_messaging: ^7.0.0

I haven't tried iOS yet.

Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.RuntimeException: PluginRegistrantCallback is not set.

how to fix?
Does Google Engineer develop?

have the same issue on android only, setting Background Message resolves the issue

@bretie, Kotlin worked for me. The procedure is the following:

  1. Improve android/app/build.gradle file:
// At the bottom of the file, you will find a `dependencies` section

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    // Required for firebase messaging
    implementation 'com.google.firebase:firebase-messaging:20.1.6'
}
  1. Create an Application class
package YOUR_PACKAGE_NAME

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService

class Application : FlutterApplication(), PluginRegistry.PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    override fun registerWith(registry: PluginRegistry?) {
        FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
    }
}
  1. In AndroidManifest.xml improve the application tag:
<!-- FROM -->
<application android:name="io.flutter.app.FlutterApplication" ... />

<!-- TO -->
<application android:name=".Application" ... />
  1. In the dart code make sure the onBackgroundMessage callback is static or out of class function.
Future<dynamic> _onBackgroundMessage(Map<String, dynamic> message) async {
  debugPrint('On background message $message');
  return Future<void>.value();
}

class _WhateverState extends State<Whatever> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onBackgroundMessage: _onBackgroundMessage,
      // ...
    );
  }
}

Thanks so much you save my life

This one worked for me

My app crashes when app is in the background or not running and receives notification.

The official flutter migration guide (https://firebase.flutter.dev/docs/migration/) is saying the following.

Ensure that you're not manually importing any Firebase Android SDK dependencies in your android/app/build.gradle files dependencies { ... } section.

e.g. remove any lines similar to: implementation 'com.google.firebase:firebase-{PRODUCT}:{VERSION}

But the solution says that we need to add the com.google.firebase:firebase-messaging to the gradle file.

How did you resolved? now using new flutter dependency : firebase_messaging: "^8.0.0-dev.6"

@xlcod I followed the migration guide and on dart code I have:

// Define a top-level named handler which background/terminated messages will call.
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print('_firebaseMessagingBackgroundHandler > message: $message');
  // call `initializeApp` before using other Firebase services.

  ...
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  // Set the background messaging handler early on, as a named top-level function
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  ...
}
Was this page helpful?
0 / 5 - 0 ratings