如何使用Firebase Cloud Messaging [英] How to use Firebase Cloud Messaging
问题描述
我找不到有关新版本的任何文档.版本7和6具有大量文档,而版本9几乎不存在.不仅我,而且大多数人都找不到它.我只是想向后台发送简单的通知.如果有人共享有关新版本的文档,我将非常高兴.还是应该使用旧版本?
I couldn't find any documents about the new version. Versions 7 and 6 have a large number of documents, while 9 is almost nonexistent. Not only me but most people couldn't find it. I just wanted to send simple notifications to the background. I would be very happy if anyone shared a document about the new version. Or should I use the old version?
推荐答案
我想您知道如何将Firebase添加到您的App.如果不是,则: https://firebase.google.com/docs/flutter/setup?platform = android
I suppose that you know how to add firebase to your App. If not: https://firebase.google.com/docs/flutter/setup?platform=android
在将Firebase添加到应用程序之后,这就是我要做的事情:
After adding firebase to the App, this is what I do :
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 :-)
}
这篇关于如何使用Firebase Cloud Messaging的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!