我正在使用 Firebase 消息传递来使用 FlutterLocalNotificationsPlugin 处理后台消息,但当我这样做时,我收到了两个通知。我收到 1 条通知来自 FlutterLocalNotificationsPlugin,另一条来自系统通知。我需要使用 FlutterLocalNotificationsPlugin 通知,因为我需要进行一些自定义,如何禁用系统默认通知?
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await init();
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
await setupFlutterNotifications();
runApp(const MyApp());
}
@pragma('vm:entry-point')
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
await setupFlutterNotifications();
print('Application background message: $message');
final title = message.notification!.title;
final body = message.notification!.body;
await notificationService.notification(message);
}
Future<void> notification(RemoteMessage message) async {
RemoteNotification? notification = message.notification!;
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
const NotificationDetails(
android: AndroidNotificationDetails(
'channel id',
'your channel name',
channelDescription: 'your channel description',
icon: 'launch_background',
),
),
);
}
我正在使用 laravel-notification-channels/fcm 作为我的 fcm 通知。我的问题的解决方案是注释掉 fcm setNotification 函数。请参考我下面的代码示例。
public function toFcm($notifiable)
{
return FcmMessage::create()
->setData([
'title' => json_encode($this->newMessage['title']),
'body' => json_encode($this->newMessage['body']),
])
// ->setNotification(\NotificationChannels\Fcm\Resources\Notification::create()
// ->setTitle($this->newMessage['title'])
// ->setBody($this->newMessage['body'])
// // ->setImage($this->newMessage['user']['image'])
// )
->setAndroid(
AndroidConfig::create()
->setFcmOptions(AndroidFcmOptions::create()->setAnalyticsLabel('analytics'))
->setPriority(AndroidMessagePriority::HIGH())
// ->setNotification(AndroidNotification::create()->setChannelId('high_importance_channel'))
)->setApns(
ApnsConfig::create()
->setFcmOptions(ApnsFcmOptions::create()->setAnalyticsLabel('analytics_ios'))
);
}
我解决了这个问题,从后端修改代码,我正在使用 django,所以删除通知
# Create message object
message = messaging.Message(
# Removed the notification
# notification=messaging.Notification(
# title=title,
# body=body,
# ),
data={
"title": title,
"body": body,
"topic": topic,
"actionButtons": action_buttons_json, # JSON string of action buttons
},
token=registration_tokens,
)
前端使用flutter本地通知示例代码 Firebase 服务
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await NotificationService().initialize();
await NotificationService().showNotification(jsonEncode(message.data));
}
class FirebaseService {
static Future<void> initialize() async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseAnalytics.instance.setAnalyticsCollectionEnabled(true);
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
await _firebaseMessaging.requestPermission(
alert: true,
badge: true,
sound: true,
);
FirebaseMessaging.instance
.getToken()
.then((value) => log("fcm token: $value"));
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
await NotificationService().initialize();
await NotificationService().showNotification(jsonEncode(message.data));
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async {
await NotificationService().initialize();
NotificationService().showNotification(jsonEncode(message.data));
});
}
}
本地通知示例代码 本地通知
Future<void> showNotification(String data) async {
Map<String, dynamic> payload = jsonDecode(data);
List<dynamic> actionButtonsJson = payload['actionButtons'] is String
? jsonDecode(payload['actionButtons'])
: payload['actionButtons'];
AndroidNotificationDetails androidDetails = AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
actions: actionButtonsJson.isNotEmpty
? actionButtonsJson.map((actionbutton) {
final _actionButton = ActionButton.fromJson(actionbutton);
return AndroidNotificationAction(
'${DateTime.now().millisecondsSinceEpoch ~/ 100}',
_actionButton.title,
cancelNotification: true,
showsUserInterface: _actionButton.showsUserInterface,
);
}).toList()
: [],
enableLights: true,
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
);
NotificationDetails notificationDetails = NotificationDetails(
android: androidDetails, iOS: DarwinNotificationDetails());
await _flutterLocalNotificationsPlugin.show(
DateTime.now().millisecondsSinceEpoch ~/ 1000,
payload['title'],
payload['body'],
notificationDetails,
payload: data);
}