最近我升级到 firebase_messaging: ^10.0.0 当应用程序未运行时,如果有通知,它会显示两次。我收到后在代码中修改了通知数据并显示出来。即使这样,我也可以看到修改和未修改的通知。我不知道该通知在哪里触发。但是当应用程序运行时,它只显示一次通知(工作正常)。这是我的代码
/*main.dart*/
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
//await Firebase.initializeApp();
// await HomePageState.handleMessage(message);
String title="${message.notification!.title}";
String body="${message.notification!.body}";
_flutterLocalNotificationsPlugin.show(0, title, body, platformChannelSpecifics, payload: jsonEncode(message.data));
AppDatabase database= await $FloorAppDatabase.databaseBuilder(Constants.dataBaseName).addMigrations([migration1to2]).build();
if(!title.toLowerCase().contains("cancelled")){
var date=DateFormat("dd-MMM-yyyy hh:mm aa").format(DateTime.now());
NotificationModel notification=NotificationModel(title: title,message: body,read: 0,date: date);
await database.notificationDao.insertNotification(notification);
}
print("Handling a background message: ${message.messageId}");
}
Future<void> main() async {
//this line make sure all the required widgets are loaded before main application starts
//SharedPreferences.setMockInitialValues({});
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
var initializationSettingsAndroid = new AndroidInitializationSettings('@mipmap/ic_notification');
var initializationSettingsIOS = new IOSInitializationSettings(onDidReceiveLocalNotification: onDidReceiveLocalNotification);
//var initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
var initializationSettings = new InitializationSettings(android: initializationSettingsAndroid,iOS: initializationSettingsIOS);
_flutterLocalNotificationsPlugin.initialize(initializationSettings,onSelectNotification: onSelectingNotification);
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
//Initializing repository and carrying forward to avoid multiple instances of database
Repository _repository = Repository();
// runApp(BlocProvider(
// create: (_) => ThemeBloc()..add(ThemeLoadStarted()),
// child: MyApp(
// repository: _repository,
// ),
// ));
SentryOptions options=SentryOptions(dsn: APIs.sentryAPI);
final SentryClient _sentry = SentryClient(options);
Future<void> _reportErrorToSentry(dynamic error, dynamic stackTrace) async {
// Print the exception to the console.
print('Caught error: $error');
await _sentry.captureException(
error,
stackTrace: stackTrace,
);
}
runZonedGuarded(() async{
// runApp(BlocProvider(
// create: (_) => ThemeBloc()..add(ThemeLoadStarted()),
// child: MyApp(
// repository: _repository,
// ),
// ));
await SentryFlutter.init(
(options) => options.dsn = APIs.sentryAPI,
appRunner: () => runApp(BlocProvider(
create: (_) => ThemeBloc()..add(ThemeLoadStarted()),
child: MyApp(
repository: _repository,
),
)),
);
}, (error, stackTrace) {
print('runZonedGuarded: Caught error in my root zone.');
FirebaseCrashlytics.instance.recordError(error, stackTrace);
_reportErrorToSentry(error,stackTrace);
});
}
应用程序.kt
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService
class Application : FlutterApplication(), PluginRegistrantCallback {
override fun registerWith(registry: PluginRegistry) {
//FirebaseCloudMessagingPluginRegistrant.registerWith(registry)
FlutterLocalNotificationPluginRegistrant.registerWith(registry)
SqflitePluginRegistrant.registerWith(registry)
}
}
我在 application.kt 中注释掉的 FirebaseCloudMessagingPluginRegistrant.kt
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin
class FirebaseCloudMessagingPluginRegistrant {
companion object {
fun registerWith(registry: PluginRegistry) {
if (alreadyRegisteredWith(registry)) {
return
}
FlutterFirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"))
}
fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
val key = FirebaseCloudMessagingPluginRegistrant::class.java.name
if (registry.hasPlugin(key)) {
return true
}
registry.registrarFor(key)
return false
}
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="**.***.***tomer">
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />-->
<!-- android:label="@string/app_label"-->
<application
android:name=".Application"
android:label="Zuzu"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config"
android:icon="@mipmap/ic_launcher">
<meta-data android:name="io.flutter.network-policy"
android:resource="@xml/network_security_config"/>
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize"
tools:targetApi="n">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</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="AIzaSyBqZ4aa************GMzHpofWKeEU"/>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="Zuzu" />
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@mipmap/ic_notification"/>
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/notification"/>
<activity
android:name="com.yalantis.ucrop.UCropActivity"
android:screenOrientation="portrait"
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>
</application>
</manifest>
答案 0 :(得分:2)
当您应该发送“数据”消息时,您似乎正在从 Firebase Messaging 发送“通知”消息。
这是通知消息和数据消息之间的区别:
<块引用>通知消息
FCM 自动代表最终用户设备显示消息 客户端应用程序。
数据消息
客户端应用负责处理数据消息。
About FCM Messages | Firebase (#Message types)
这就解释了为什么你会得到通知的未修改版本(这是来自通知消息的自动显示)和通知的修改版本(这是你自己处理通知的代码)。
解决方案:
您需要从后端发送数据消息。 因此,如果您之前将此作为通知负载:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}
您应该将其更改为:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}
}