firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.46k stars 3.91k forks source link

[firebase_messaging] PluginRegistrantCallback is not set on Android #2077

Closed creativecreatorormaybenot closed 2 years ago

creativecreatorormaybenot commented 4 years ago
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)
ClevercodeTech commented 4 years ago

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): 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` ```
azabazay commented 4 years ago

same issue, is there any solution yet?

h0x539 commented 4 years ago
Application.java replace: ```java 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: ```java 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")); } } ```
ClevercodeTech commented 4 years ago

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:

` `

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): 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) ````
creativecreatorormaybenot commented 4 years ago

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

ClevercodeTech commented 4 years ago

@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.

h0x539 commented 4 years ago

@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

ClevercodeTech commented 4 years ago

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"

<application android:name="io.flutter.app.FlutterApplication" android:name=".Application"
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">
<meta-data android:name="io.flutter.app.android.SplashScreenUntilFirstFrame" android:value="true" />

      <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>     

kalibu commented 4 years ago

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

helenaford commented 4 years ago

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

creativecreatorormaybenot commented 4 years ago

@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..

helenaford commented 4 years ago

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

creativecreatorormaybenot commented 4 years ago

@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.

ClevercodeTech commented 4 years ago

@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<String, dynamic> message) async {
        print("onMessage: $message");
      },
      onBackgroundMessage: platform == TargetPlatform.iOS ? null : myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> 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<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
    print(message);
    return Future<void>.value();
  }

}
creativecreatorormaybenot commented 4 years ago

@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.

demon-zhonglin commented 4 years ago

@ClevercodeTech Can you provide detailed instructions?

ClevercodeTech commented 4 years ago

@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"));
}
}
lexdevel commented 4 years ago

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

ClevercodeTech commented 4 years ago

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

could you please post your code.

lexdevel commented 4 years ago

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'

    // ...
}
ClevercodeTech commented 4 years ago

have you included

// under [project]/android/app/build.gradle
apply plugin: 'com.google.gms.google-services'
lexdevel commented 4 years ago

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"
ClevercodeTech commented 4 years ago

@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>   
lexdevel commented 4 years ago

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

ClevercodeTech commented 4 years ago

@lexdevel please post your error.

lexdevel commented 4 years ago

@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)
ClevercodeTech commented 4 years ago

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();
  }
lexdevel commented 4 years ago

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.

ClevercodeTech commented 4 years ago

@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
lexdevel commented 4 years ago

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.

ClevercodeTech commented 4 years ago

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;
    }
}
lexdevel commented 4 years ago

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.

ClevercodeTech commented 4 years ago

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'  
}
lexdevel commented 4 years ago

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.

irediaes commented 4 years ago

@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.

lexdevel commented 4 years ago

@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.

LasseRosenow commented 4 years ago

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.

lexdevel commented 4 years ago

@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.

brainlabsweb commented 4 years ago

@ClevercodeTech changing

from

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

to

android:name=".Application"

to resolved my issue

Pactera-wanpingzhang commented 4 years ago

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.

ghost commented 4 years ago

@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.

ClevercodeTech commented 4 years ago

@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.

ghost commented 4 years ago

@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?

ClevercodeTech commented 4 years ago

@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.

lexdevel commented 4 years ago

@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'

}


2. Create an `Application` class
```kotlin
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" ... />

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


4. In the `dart` code make sure the `onBackgroundMessage` callback is static or out of class function.
```dart
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,
      // ...
    );
  }
}
lexdevel commented 4 years ago

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

dineufeld commented 3 years ago

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

efraespada commented 3 years ago

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.

ElaineSchwner commented 3 years ago

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);

ngoluuduythai commented 3 years ago

@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