[英]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.