我正在使用Flutter应用程序,并且已经实现了Firebase云消息传递,以接收从服务器发送的消息。我正在使用flutter_local_notifications包。我引用了-https://pub.dev/packages/flutter_local_notifications/example以获取通知,引用了https://firebase.flutter.dev/docs/messaging/usage#foreground-messages:~:text = found%20here. -,Message%20types,-%23以获取云消息传递。
在我的主. dart -
Future<void> _messageHandler(RemoteMessage message) async {
print('background message ${message.notification!.body}');
}
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
await setupFlutterNotifications();
showFlutterNotification(message);
// 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.
print('Handling a background message ${message.messageId}');
}
/// Create a [AndroidNotificationChannel] for heads up notifications
late AndroidNotificationChannel channel;
bool isFlutterLocalNotificationsInitialized = false;
Future<void> setupFlutterNotifications() async {
if (isFlutterLocalNotificationsInitialized) {
return;
}
channel = const AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
// 'This channel is used for important notifications.', // description
importance: Importance.high,
);
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
/// Update the iOS foreground notification presentation options to allow
/// heads up notifications.
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
isFlutterLocalNotificationsInitialized = true;
}
void showFlutterNotification(RemoteMessage message) {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
if (notification != null && android != null && !kIsWeb) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
// channel.description,
icon: 'launch_background',
),
),
);
}
}
_configureForegroundMessaging(){
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
log('new notificaiton: ${message.data}');
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android!;
// If `onMessage` is triggered with a notification, construct our own
// local notification to show to users using the created channel.
if (notification != null && android != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
// channel.description,
icon: android.smallIcon,
// other properties...
),
));
}
});
}
/// Initialize the [FlutterLocalNotificationsPlugin] package.
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// Set the background messaging handler early on, as a named top-level function
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
if (!kIsWeb) {
await setupFlutterNotifications();
}
_configureForegroundMessaging();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
await _initializePrefs();
runApp(const MyApp());
}
机器人清单.xml-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.blog_app">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:label="blog_app"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
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">
<!-- 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"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"
android:exported="true">
</receiver>
<service
android:name=".java.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- 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.firebase.messaging.default_notification_channel_id"
android:value="high_importance_channel" />
</application>
</manifest>
发送通知时,应用程序崩溃,我收到以下错误-
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): java.lang.IllegalArgumentException: com.example.blog_app: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at android.app.PendingIntent.checkFlags(PendingIntent.java:382)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:465)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at android.app.PendingIntent.getActivity(PendingIntent.java:451)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at android.app.PendingIntent.getActivity(PendingIntent.java:415)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:176)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:820)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1109)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:996)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:262)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:319)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(Unknown Source:12)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at android.os.Handler.handleCallback(Handler.java:938)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at android.os.Handler.dispatchMessage(Handler.java:99)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at android.os.Looper.loopOnce(Looper.java:226)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at android.os.Looper.loop(Looper.java:313)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at android.app.ActivityThread.main(ActivityThread.java:8663)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
E/MethodChannel#dexterous.com/flutter/local_notifications(25254): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
D/AndroidRuntime(25254): Shutting down VM
E/AndroidRuntime(25254): FATAL EXCEPTION: main
E/AndroidRuntime(25254): Process: com.example.blog_app, PID: 25254
E/AndroidRuntime(25254): java.lang.RuntimeException: Unable to create service com.example.blog_app.java.MyFirebaseMessagingService: java.lang.ClassNotFoundException: Didn't find class "com.example.blog_app.java.MyFirebaseMessagingService" on path: DexPathList[[zip file "/data/app/~~JLhSAfO9gLJElJK0cBbFwA==/com.example.blog_app-WTmVE1_SbB9GDNb1kBivcQ==/base.apk"],nativeLibraryDirectories=[/data/app/~~JLhSAfO9gLJElJK0cBbFwA==/com.example.blog_app-WTmVE1_SbB9GDNb1kBivcQ==/lib/arm64, /data/app/~~JLhSAfO9gLJElJK0cBbFwA==/com.example.blog_app-WTmVE1_SbB9GDNb1kBivcQ==/base.apk!/lib/arm64-v8a, /system/lib64, /system/system_ext/lib64]]
E/AndroidRuntime(25254): at android.app.ActivityThread.handleCreateService(ActivityThread.java:4953)
E/AndroidRuntime(25254): at android.app.ActivityThread.access$1800(ActivityThread.java:310)
E/AndroidRuntime(25254): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2300)
E/AndroidRuntime(25254): at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(25254): at android.os.Looper.loopOnce(Looper.java:226)
E/AndroidRuntime(25254): at android.os.Looper.loop(Looper.java:313)
E/AndroidRuntime(25254): at android.app.ActivityThread.main(ActivityThread.java:8663)
E/AndroidRuntime(25254): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(25254): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
E/AndroidRuntime(25254): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)
E/AndroidRuntime(25254): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.blog_app.java.MyFirebaseMessagingService" on path: DexPathList[[zip file "/data/app/~~JLhSAfO9gLJElJK0cBbFwA==/com.example.blog_app-WTmVE1_SbB9GDNb1kBivcQ==/base.apk"],nativeLibraryDirectories=[/data/app/~~JLhSAfO9gLJElJK0cBbFwA==/com.example.blog_app-WTmVE1_SbB9GDNb1kBivcQ==/lib/arm64, /data/app/~~JLhSAfO9gLJElJK0cBbFwA==/com.example.blog_app-WTmVE1_SbB9GDNb1kBivcQ==/base.apk!/lib/arm64-v8a, /system/lib64, /system/system_ext/lib64]]
E/AndroidRuntime(25254): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:259)
E/AndroidRuntime(25254): at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
E/AndroidRuntime(25254): at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/AndroidRuntime(25254): at android.app.AppComponentFactory.instantiateService(AppComponentFactory.java:129)
E/AndroidRuntime(25254): at androidx.core.app.CoreComponentFactory.instantiateService(CoreComponentFactory.java:75)
E/AndroidRuntime(25254): at android.app.ActivityThread.handleCreateService(ActivityThread.java:4922)
E/AndroidRuntime(25254): ... 9 more
I/Process (25254): Sending signal. PID: 25254 SIG: 9
Lost connection to device.
Exited (sigterm)
出现此错误后,通知会出现在手机的通知栏中(当应用程序被关闭或处于后台时),而当应用程序处于前台时,通知根本不会出现(尽管我已将其配置为显示。)
我搜索了这个问题,但是在Flutter中没有找到任何与这个问题相关的东西。请帮助我解决这个问题!
1条答案
按热度按时间r9f1avp51#
更新您的flutter_local_notifications包,在我的情况下,它是通过版本解决的: