我在 Flutter 2.0 中遇到了 Firebase Cloud Messaging onMessage 的问题。
功能
FirebaseMessaging.onMessage.listen((RemoteMessage message) { ... }
在前台接收消息时不调用。但是,日志说
收到消息的广播
在收到第一条消息时,我会收到其他警告,例如:
访问隐藏方法 Landroid/os/WorkSource
但是警告会在随后的消息中消失。
有趣的是,那
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
作品。
如果我将应用程序发送到后台,我会收到通知并调用定义的方法。
代码
@override
void initState() {
initializeFlutterFire()
.then((value) => subscribeToMessages);
super.initState();
}
Future<void> initializeFlutterFire() async {
try {
Firebase.initializeApp();
setState(() {
_initialized = true;
print("Firebase has been initialized");
});
} catch (e) {
setState(() {
_error = true;
});
}
}
void subscribeToMessages() {
// The following handler is called, when App is in the background.
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
// The following function is not called, when a message was received by the device.
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}');
}
});
}
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
print('message from background handler');
print("Handling a background message: ${message.messageId}");
}
我有一种感觉,onMessage().listen(...) 没有订阅,这就是为什么没有执行任何操作。
你有什么建议,我做错了什么?
提前致谢, 乌韦
环境
Firebase 控制台云消息传递
上
华为 P20 和三星 Galaxy Tab A 10,均在 Android 10 上。
发布规范.yaml
firebase_core: "^1.0.1"
firebase_messaging: "^9.0.0"
安卓/build.gradle
dependencies {
...
classpath 'com.google.gms:google-services:4.3.5'
android/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
...
android {
compileSdkVersion 30
...
defaultConfig {
minSdkVersion 16
targetSdkVersion 30
...
AndroidManifest.xml
<activity ...>
...
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</activity>
扑医生
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, 2.0.2, on macOS 11.2.1 20D75 darwin-x64, locale de)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[!] Xcode - develop for iOS and macOS
✗ Xcode installation is incomplete; a full installation is necessary for iOS development.
Download at: https://developer.apple.com/xcode/download/
Or install Xcode via the App Store.
Once installed, run:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
sudo xcodebuild -runFirstLaunch
[✓] Chrome - develop for the web
[✓] Android Studio
[✓] Android Studio (version 4.1)
[✓] IntelliJ IDEA Community Edition (version 2020.1.2)
[✓] VS Code (version 1.53.0)
[✓] Connected device (3 available)
! Doctor found issues in 1 category.