簡體   English   中英

如何使用 Firebase 雲消息

[英]How to use Firebase Cloud Messaging

我找不到任何關於新版本的文件。 版本 7 和 6 有大量文檔,而版本 9 幾乎不存在。 不僅我,大多數人都找不到。 我只是想向后台發送簡單的通知。 如果有人分享有關新版本的文檔,我會非常高興。 還是我應該使用舊版本?

我創建了一個示例應用程序,展示了如何在版本 9 上使用 FCM 實現通知系統。

你可以參考這個項目,如果你需要更多信息,我會編輯這個答案!

我想您知道如何將 firebase 添加到您的應用程序中。 如果沒有:https://firebase.google.com/docs/flutter/setup?platform=android

將 firebase 添加到 App 后,我是這樣做的:

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

  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      routes: {
      '/': (context) =>  AppStarter(),
      '/message': (context) => NotificationDetails(),
      },
     ),
    );
   }



class AppStarter extends StatefulWidget{
   @override
   _AppStarterState createState() => _AppStarterState();
  }



class _AppStarterState extends State<AppStarter>
   {

     FirebaseMessaging messaging = FirebaseMessaging.instance;

    Future<void> showMeMyToken()
    async {
      var myToken = await messaging.getToken();
      print("My Token is: " + myToken.toString());
    }


    @override
    void initState() {
       super.initState();

       showMeMyToken();

      FirebaseMessaging.instance.getInitialMessage().then((value) {
       if(value != null)
        {
          Navigator.push(context,
          MaterialPageRoute(
              builder: (context){return NotificationDetails();},
          settings: RouteSettings(arguments: value.data,),
         ),
        );
       }
     });


     FirebaseMessaging.onMessage.listen((RemoteMessage message) {


        if (message.notification != null) {
           print('Message on Foreground: ${message.notification}');
              }
         });


      FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message)
       {
         Navigator.push(
           context,
           MaterialPageRoute(
               builder: (context) {return NotificationDetails();},
               settings: RouteSettings(arguments: message.data,)
          ),
        );
     });

     FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
   }


   @override
    Widget build(BuildContext context) {

      return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Just a Test',
        
        home: AppHome(),
       );
      }
   }




   Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
     await Firebase.initializeApp();

      print("Handling a background message :-): ${message.data}");
      //Here you can do what you want with the message :-)
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM