简体   繁体   English

Firebase 消息在应用程序在后台和前台运行时有效。 但是,当应用程序终止时没有通知

[英]Firebase message works when app in background and foreground. However when app terminated no notifications

I am new to flutter and firebase and have followed the documentation best I could.我是 flutter 和 firebase 的新手,并且尽我所能遵循文档。 FCM seems to work when the app is in the foreground and background.当应用程序位于前台和后台时,FCM 似乎工作。 However, when the app is terminated I do not get any notifications.但是,当应用程序终止时,我没有收到任何通知。 I have looked at the app permissions etc and all seem to be fine.我查看了应用程序权限等,一切似乎都很好。

pubspec.yml firebase_messaging: ^11.2.5 pubspec.yml firebase_messaging:^11.2.5

class PushNotificationService {
  final FirebaseMessaging messaging = FirebaseMessaging.instance;

  Future initialize() async {

    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );


    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
    } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
      print('User granted provisional permission');
    } else {
      print('User declined or has not accepted permission');
    }

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });
  }
}

main.dart main.dart

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Handling a background message: ${message.messageId}");
}




Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: const FirebaseOptions(
      apiKey: "",
      authDomain: '',
      databaseURL: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: '',
      appId: "",
      measurementId: '',
    ),
  );

  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  const AndroidNotificationChannel channel = AndroidNotificationChannel(
    'high_importance_channel', // id
    'High Importance Notifications', // title
     description: 'This channel is used for important notifications.', // description
     importance: Importance.high,
  );

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();

  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  runApp(MyApp());
}

home.dart主页.dart

class _HomeTabState extends State<HomeTab> {


  void pushnotifications()async{
    PushNotificationService pushNotificationService=PushNotificationService();
    pushNotificationService.initialize();
    pushNotificationService.getToken();
  }




  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    pushnotifications();

  }

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

Androidmanifest安卓清单

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>


   <application
        android:label=""
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
             <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <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>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />

       <meta-data android:name="com.google.android.geo.API_KEY"
           android:value=""/>

       <meta-data
           android:name="com.google.firebase.messaging.default_notification_channel_id"
           android:value="high_importance_channel" />
    </application>
</manifest>

Json Payload Json 有效载荷

{
    "to": "",
    "notification": {
        "body": "This is the body",
        "title": "This is the title"
    },
    "priority": "high"
}

You should probably also add a listener for getInitialMessage() on firebase message instance.您可能还应该在 firebase 消息实例上为getInitialMessage()添加一个侦听器。 This will fetch the notifications when app is terminated.这将在应用程序终止时获取通知。

FirebaseMessaging.instance
        .getInitialMessage()
        .then((RemoteMessage? message) {
      if (message != null) {
        Navigator.pushNamed(
          context,
          '/message',
          arguments: MessageArguments(message, true),
        );
      }
    });

Refer: https://pub.dev/packages/firebase_messaging/example参考: https://pub.dev/packages/firebase_messaging/example

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter,Firebase ios,当应用程序在后台时,云消息不显示,仅当应用程序在前台时 - Flutter, Firebase ios, cloud message doesn't show when app in background, only if app in foreground Firebase 应用程序终止时推送通知回调不起作用 - Firebase push notifications callback doesn't work when app is terminated Firebase 应用程序终止时未调用消息后台处理程序(颤振) - Firebase messaging background handler not called when app is terminated (Flutter) 应用程序终止时的 FCM 推送通知 FLUTTER - FCM push notifications FLUTTER when app is terminated FIREBASE_MESSAGING:当应用程序处于后台或已终止时,onBackgroundMessage 不处理通知 - FIREBASE_MESSAGING: onBackgroundMessage not handling notification when app is on Background or Terminated Flutter 应用程序在前台接收到 Firebase 推送通知时显示错误:“此处不支持读取 NULL 字符串。” - Flutter app when receiving firebase push notifications in foreground shows the error: "Reading a NULL string not supported here." 当应用程序在前台时,firebase 消息不显示通知 - firebase messaging not showing notification when the app is in foreground 当应用程序在前台使用 ZB12E1515C25C7D8C0352F1413AB9A15Z 通知 android - Notification is coming sometimes and sometimes not coming when the app is in foreground using firebase notifications in Flutter for android Flutter 应用程序终止时在后台获取 API - Flutter Fetch API in background when App is terminated 当应用程序在后台并在前台接收时,为什么在 IOS 上收不到 FCM 通知? Flutter - Why does not receive FCM notifications on IOS when the app is in background and receive in foreground? Flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM