Flutter Firebase Messaging не может создать службу io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService - PullRequest
1 голос
/ 22 сентября 2019

Я пытаюсь использовать Firebase Messaging в приложении Flutter.Я следую всем инструкциям из пакета.

В моем pubspec.yaml у меня есть следующие пакеты:

dependencies:
  flutter:
    sdk: flutter
  ...
  firebase_messaging: ^5.1.5
  ...

Мой main.app - это просто:

void main() {
  runApp(MyApp());
}

MyApp - это StatefullWidget и внутри _MyAppStateУ меня есть:

    FirebaseMessaging firebaseMessaging = FirebaseMessaging();
   @override
  void initState() {
    super.initState();
    NotificationHandler().initializeFcmNotification();
  }

Весь код находится внутри уведомлений_handler.dart (благодаря @HarishPenta):

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

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

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

  Future<dynamic> myBackgroundMessageHandler(
      Map<String, dynamic> message) async {
    print("onLaunch: $message");
    // Or do other work.
  }

  initializeFcmNotification() async {
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();

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

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

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

    _fcm.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
      },
      //onBackgroundMessage: myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );
  }

...}

В моем AndroidManifest.xml у меня есть:

<activity
            android:name=".MainActivity"
...
<intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

и, наконец, внутри приложения / src / main / java // Application.java У меня есть:

package <my ID app>;  --> the same ID in google-services.json

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.GeneratedPluginRegistrant;

import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;


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

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

Ну, приложение запускается нормально, и на переднем плане, когда я отправляюуведомление, приложение останавливается, и я вижу это сообщение об ошибке:

D/AndroidRuntime(26933): Shutting down VM
E/AndroidRuntime(26933): FATAL EXCEPTION: main
E/AndroidRuntime(26933): Process: br.com.htsnet.emergencia, PID: 26933
E/AndroidRuntime(26933): java.lang.RuntimeException: Unable to create service io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService: java.lang.RuntimeException: PluginRegistrantCallback is not set.
E/AndroidRuntime(26933):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3167)
E/AndroidRuntime(26933):    at android.app.ActivityThread.access$1900(ActivityThread.java:177)
E/AndroidRuntime(26933):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1532)
E/AndroidRuntime(26933):    at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(26933):    at android.os.Looper.loop(Looper.java:145)
E/AndroidRuntime(26933):    at android.app.ActivityThread.main(ActivityThread.java:5951)
E/AndroidRuntime(26933):    at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(26933):    at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime(26933):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
E/AndroidRuntime(26933):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
E/AndroidRuntime(26933): Caused by: java.lang.RuntimeException: PluginRegistrantCallback is not set.
E/AndroidRuntime(26933):    at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.startBackgroundIsolate(FlutterFirebaseMessagingService.java:157)
E/AndroidRuntime(26933):    at io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService.onCreate(FlutterFirebaseMessagingService.java:77)
E/AndroidRuntime(26933):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3157)
E/AndroidRuntime(26933):    ... 9 more

Я использую Android Studio 3.5, функции Firebase для отправки уведомлений с данными в полезной нагрузке (click_action: 'FLUTTER_NOTIFICATION_CLICK').

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...