#android #firebase #flutter #push-notification
# #Android #firebase #flutter #push-уведомление
Вопрос:
Я хочу сохранить входящее сообщение firebase в базе данных локально, и оно отлично работает для onMessage, onLaunch и onResume, но onBackgroundMessage вообще не запускается при попытке отладки, но когда мое приложение работает в фоновом режиме, я могу получить уведомление в панели уведомлений
Push-уведомление
Future<dynamic> backgroundMessageHandler(Map<String, dynamic> message) async {
if (message.containsKey('data')) {
print({message});
PushNotificationService().storeInDatabase(message);
final notifications = await PushNotificationService().getNotifications();
final reversedNotifications = notifications.reversed.toList();
homeScreenBloc.activityController.add(reversedNotifications);
}
}
class PushNotificationService {
BuildContext context;
final FirebaseMessaging _fcm = FirebaseMessaging();
Future initialise() async {
// print('notifcations length = ${notifications.length}');
// context = ctx;
final notifications = await getNotifications();
if (notifications != null) {
homeScreenBloc.activityController.add(notifications);
}
if (Platform.isIOS) {
_fcm.requestNotificationPermissions(IosNotificationSettings());
}
_fcm.configure(
onMessage: (Map<String, dynamic> message) async {
print({message});
storeInDatabase(message);
final notifications = await getNotifications();
final reversedNotifications = notifications.reversed.toList();
homeScreenBloc.activityController.add(reversedNotifications);
}
/// called when the notification is clicked while the app is in running in foreground
/// notification fields sends title and body but for other two cases its blank
/// so need to send in data field
,
// called when the notification is clicked while the app is closed(not running)
onLaunch: (Map<String, dynamic> message) async {
print({message});
storeInDatabase(message);
final notifications = await getNotifications();
final reversedNotifications = notifications.reversed.toList();
homeScreenBloc.activityController.add(reversedNotifications);
},
// called when the notification is clicked while the app is running in the background
onResume: (Map<String, dynamic> message) async {
print({message});
storeInDatabase(message);
final notifications = await getNotifications();
final reversedNotifications = notifications.reversed.toList();
homeScreenBloc.activityController.add(reversedNotifications);
},
// called while the app is running in the background
onBackgroundMessage: Platform.isIOS ? null : backgroundMessageHandler,
// }
);
}
AndroidManifest.xml
<application android:usesCleartextTraffic="true" android:name=".Application" ....
Application.kt
package com.altorumleren.alfinityiot;
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.firebasemessaging.FlutterFirebaseMessagingService;
public class Application extends FlutterApplication implements PluginRegistrantCallback {
@Override
public void onCreate() {
super.onCreate();
FlutterFirebaseMessagingService.setPluginRegistrant(this);
}
@Override
public void registerWith(PluginRegistry registry) {
GeneratedPluginRegistrant.registerWith(registry);
}
}
build.gradle
dependencies {
implementation 'com.google.firebase:firebase-messaging:<21.0.0>'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation "com.google.firebase:firebase-messaging:20.2.4"
}
Журналы при запуске приложения
Launching libmain.dart on AOSP on IA Emulator in debug mode...
libmain.dart:1
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
e: C:UsersadityDesktopalfinityandroidappsrcmainkotlincomexamplealfinityApplication.kt: (9, 26): Expecting a top level declaration
e: C:UsersadityDesktopalfinityandroidappsrcmainkotlincomexamplealfinityApplication.kt: (9, 34): Expecting a top level declaration
e: C:UsersadityDesktopalfinityandroidappsrcmainkotlincomexamplealfinityApplication.kt: (9, 53): Expecting a top level declaration
e: C:UsersadityDesktopalfinityandroidappsrcmainkotlincomexamplealfinityApplication.kt: (9, 64): Expecting a top level declaration
e: C:UsersadityDesktopalfinityandroidappsrcmainkotlincomexamplealfinityApplication.kt: (9, 89): Expecting a top level declaration
e: C:UsersadityDesktopalfinityandroidappsrcmainkotlincomexamplealfinityApplication.kt: (9, 89): Function declaration must have a name
e: C:UsersadityDesktopalfinityandroidappsrcmainkotlincomexamplealfinityApplication.kt: (17, 51): Expecting an element
e: C:UsersadityDesktopalfinityandroidappsrcmainkotlincomexamplealfinityApplication.kt: (10, 3): This annotation is not applicable to target 'expression'
Комментарии:
1. Вы нашли решение?
Ответ №1:
Похоже, вы не упомянули о своей полезной нагрузке, но для запуска onBackgroundMessege вам нужно убедиться, что ваша полезная нагрузка не содержит уведомлений. Например:
const payload = {
data: {
title: 'title',
body: 'body',
}
}