【问题标题】:Flutter App Firebase push notification not coming in backgroundFlutter App Firebase 推送通知未在后台出现
【发布时间】:2023-04-11 04:11:02
【问题描述】:

当应用终止/从后台从最近的应用中删除时,我面临收到通知的问题。

我已经在应用或项目级别的 build.gradle 文件中完成了 android 应用所需的所有设置。当应用打开或应用在最近的应用中时,我能够收到推送通知。

库版本

firebase_messaging: ^11.2.0
firebase_core: ^1.10.0
flutter_local_notifications: ^9.1.4

这是我的代码。

await Firebase.initializeApp();
    FirebaseMessaging messaging = FirebaseMessaging.instance;

    messaging.getToken().then((value) {
      print('firebase token =$value');    
    });

    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      //print(event.notification!.body);
      RemoteNotification? notification = message.notification;
      if (notification != null) {
        print("Notification received when app in foreground");
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      print('Message clicked!');
    });

    await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );

BackgroundMessage 处理程序代码如下

Future<void> _messageHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  RemoteNotification? notification = message.notification;
  if (notification != null) {
    print("Notification received when app in background");
  }
}

下面是我完整的 main.dart 文件代码

Future<void> _messageHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  RemoteNotification? notification = message.notification;
  if (notification != null) {
    print("Notification received when app in background");
  }
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_messageHandler);
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool isUserLoggedIn = true;
  bool isLogoutAlertShown = false;
  final materialAppKey = GlobalKey();
  late FirebaseMessaging messaging;


  @override
  void initState() {
    super.initState();
    setUpNotification();
  }

  setUpNotification() async {
    messaging = FirebaseMessaging.instance;
    messaging.getToken().then((value) {
      print('firebase token =$value');
      //sendTokenToServer(value);
      Pref.setFcmToken(token: '$value');
    });
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      //print(event.notification!.body);
      RemoteNotification? notification = message.notification;
      if (notification != null) {
        print("Notification received when app in foreground");
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      print('Message clicked!');
    });
   await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    return _materialApp();
  }

  Widget _materialApp() {
    return FutureBuilder(
        future: _loginState(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return MaterialApp(
              debugShowCheckedModeBanner: false,
              key: materialAppKey,
              darkTheme: AppTheme.lightTheme,
              theme: AppTheme.lightTheme,
              home: isUserLoggedIn == true ? 
              BottomNavigationContainer() : LoginOptions(),
            );
          } else {
            return Container(color: Colors.white);
          }
        });
  }

  Future<void> _loginState() async {
    final token = await Pref.getToken();
    isUserLoggedIn = token.length > 0 ? true : false;
  }
}

建议我缺少什么或做错了什么。

【问题讨论】:

  • 添加main.dart文件代码。
  • main.dart 文件代码更新@Yashraj
  • 在 main() 中添加这一行:FirebaseMessaging.onBackgroundMessage(_messageHandler);
  • 已添加但当我从最近的应用程序中删除该应用程序时仍然无法正常工作。 @Yashraj
  • 至少在 Android 上这需要实现 MessagingService ...这是白名单,以便能够在后台运行(即使 Activity 未运行)。虽然我假设这可能是一个重复的 Q,但没有搜索过……假设一个未运行的应用程序可以处理后台消息,这完全没有意义。

标签: android firebase flutter push-notification firebase-cloud-messaging


【解决方案1】:

感谢大家的回复。

我找到了为什么我的后台处理程序无法工作的解决方案,因为我在调试模式下运行我的应用程序。根据 FlutterFire Cloud messaging Doc 后台方法,如果您杀死您的应用程序,则在调试模式下不起作用。

您可以通过在调试中运行您的应用程序来测试您的后台处理程序方法,然后通过切换应用程序使其不再在前台运行。

如果您想在最近的任务中检查应用程序终止/终止后,请在 发布模式 下运行应用程序。效果很好

再次感谢大家。

【讨论】:

  • 另一种方法是再次打开应用程序并关闭它,因此它将作为终止应用程序运行。
  • 我在调试模式上浪费时间。这个答案应该是关于这个问题的唯一答案。上帝保佑你!
猜你喜欢
  • 2022-01-03
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
  • 1970-01-01
  • 2017-11-06
  • 2022-09-27
  • 2021-06-13
  • 1970-01-01
相关资源
最近更新 更多