Firebase Messaging 是 Firebase 平台中的一個服務,可以在 Flutter 應用中實作推送通知功能。與其他推送通知服務相比,Firebase Messaging 提供了許多優勢,例如:支援 Android 和 iOS 兩個平台、支援實時通知、可以與 Firebase 其他服務(例如 Firebase Cloud Messaging)結合使用等。
使用firebase_message(https://firebase.google.com/docs/cloud-messaging/flutter/client)的前提是先要去firebase背景建立項目,擷取到android(google-services.json放到android-app目錄下)和ios(GoogleService-Info.plist放到ios的Runner目錄下)的配置檔案,國内的安卓手機需要安裝Google Service才可以。記住要申請權限
使用步驟:
1、添加依賴:firebase_messaging: ^14.1.4;
2、擷取fcmtoken:final fcmToken = await FirebaseMessaging.instance.getToken();
3、接收消息:
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
LogUtil.v('firebase Got a message whilst in the foreground!');
LogUtil.v('firebase Message data: ${message.data}');
/// 配合flutter_local_notification顯示系統通知
_showLocalNotification(message);
});
// It is assumed that all messages contain a data field with the key 'type'
Future<void> _setupInteractedMessage() async {
await notificationUtils.initNotification();
// Get any messages which caused the application to open from
// a terminated state.
RemoteMessage? initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
// If the message also contains a data property with a "type" of "chat",
// navigate to a chat screen
if (initialMessage != null) {
_handleMessage(initialMessage);
}
// Also handle any interaction when the app is in the background via a
// Stream listener
FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
}
void _handleMessage(RemoteMessage message) {
LogUtil.v("firebase _handleMessage : ${message.data}");
_showLocalNotification(message);
}
如果想要接收背景消息,記住:
- 它不能是匿名函數。
- 它必須是頂級函數(例如,不是需要初始化的類方法)。
- 它必須@pragma('vm:entry-point')在函數聲明的正上方注釋(否則它可能會在釋出模式的搖樹優化過程中被删除)。
我是在main.dart中做的:
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
LogUtil.v("firebase Handling a background message: ${message.messageId}");
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
}