应用程序被终止时 FCM 通知不会触发

ban*_*ang 7 android dart flutter firebase-cloud-messaging

当应用程序位于后台或前台时,FCM 通知对我有用,但当应用程序被终止时,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();
  }
Run Code Online (Sandbox Code Playgroud)

我在网上和 stackoverflow 上阅读了很多文章。例如,其中一项建议是禁用电池保护程序。我已经尝试过,但没有运气。我缺少什么想法吗?

我正在使用 firebase-messaging 版本^10.0.2

Ste*_*wie 7

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

由于处理程序在应用程序上下文之外以自己的隔离方式运行,因此无法更新应用程序状态或执行任何 影响 UI 的逻辑。但是,您可以执行 HTTP 请求、IO 操作(更新本地存储)、与其他插件通信等逻辑。

您应该在之前设置后台消息处理程序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());
}
Run Code Online (Sandbox Code Playgroud)

详细信息请查看此内容


ema*_*ndt 0

当应用程序被杀死时,当 FCM 想要触发某些行为时“做某事”的唯一方法是使用 BroadcastReceiver:https://chloe-thhsu.medium.com/a-simple-way-to-combine-fcm- notification-with-tts-b48a777ec84f(在此链接中您只需要一段示例代码)

FCM 应该触发一些 Intent,只有注册的应用程序才会收到它并执行某些操作。

即使应用程序关闭/终止,广播接收器也可以工作,但它们在触发时只允许基本的“操作”。对于您来说,它可能是可用的:“通过传递 XYZ 参数使用意图启动和活动”,您的应用程序/活动将在其中启动,您可以从那里执行“所有您想要的操作”。