android - 应用程序被杀死时没有触发 FCM 通知

标签 android flutter dart firebase-cloud-messaging

当应用程序处于后台或前台时,FCM 通知对我有效,但在应用程序被终止时无效。
这是我的 FCM 配置代码:

 Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Handling a background message: ${message.messageId}");
}
class CategoriesScreen extends StatefulWidget {
  static const routeName = '/view-cateogries';
  _CategoriesScreenState createState() => _CategoriesScreenState();
}

class _CategoriesScreenState extends State<CategoriesScreen> {
  Future _screenFuture;
  void initState() {
    _saveDeviceToken(FirebaseMessaging.instance);
     FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    super.initState();
  }
我已经在网上和 stackoverflow 上阅读了许多文章。例如,其中一项建议是禁用电池保护程序。我试过了,但没有运气。有什么我想念的想法吗?
我正在使用 firebase-messaging 版本 ^10.0.2

最佳答案

看起来您正在调用 FirebaseMessaging.onBackgroundMessage()内部方法initState()如文档中所述,不允许使用有状态小部件:

Since the handler runs in its own isolate outside your applications context, it is not possible to update application state or execute any UI impacting logic. You can however perform logic such as HTTP requests, IO operations (updating local storage), communicate with other plugins etc.


您应该在 runApp() 之前设置后台消息处理程序:
/// Define a top-level named handler which background/terminated messages will
/// call.
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();
  print("Handling a background message: ${message.messageId}");
}

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Initialize Firebase App
  await Firebase.initializeApp();

  // Set the background messaging handler early on, as a named top-level function
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  // Run your app
  runApp(HomeScreen());
}
查看this详情。

关于android - 应用程序被杀死时没有触发 FCM 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67860332/

相关文章:

android - 当条件成立时,Flutter 重定向到新屏幕

constructor - Dart (/flutter ): Create function in initializer list

android - 在 Android Studio 上构建失败

java - 如何将字母附加到资源文件

android - Flutter-dart http 库 ClientException

Flutter Provider - 使用 ProxyProvider 的循环依赖

java - 如何指定 android.os.Message 的目的地?

java - Android解析Plist文件

android - 在 Flutter for Android 中设计 UI

dart - 向 Material 文本字段添加芯片