Flutter应用程序Firebase推送通知在后台未能到达。

6

当应用程序终止或从后台“最近使用的应用程序”中删除时,我遇到了无法接收通知的问题。

我已经在build.gradle文件中的app或项目级别完成了所有必需的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;
  }
}

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


谢谢您的回复。您能否建议我如何实现此服务,以便在应用程序未运行时后台接收通知。@MartinZeitler - sunil Kumawat
谢谢您的回复。我已经检查了设置,它正在工作。对于后台消息,我们只需要添加背景方法,Flutter会自动生成通知,如果我们添加了这个方法。@mariofrancois - sunil Kumawat
你能重启一下安卓手机,然后再检查一次吗? - Hardik Mehta
你尝试在其他设备上了吗? 你使用的是哪个设备? - Yashraj
我已经在三个不同的设备和版本上尝试过了。红米Note 9(版本10),红米Note 8(版本11)和Oppo A5(版本9)@Yashraj - sunil Kumawat
显示剩余10条评论
2个回答

17

感谢大家的回复。

我找到了解决方案,为什么我的后台处理程序没有工作,因为我正在调试模式下运行我的应用程序。根据FlutterFire Cloud messaging文档,如果你杀掉你的应用程序,在调试模式下后台方法将不起作用。

您可以通过在调试模式下运行应用程序,然后将其转换为后台应用程序来测试您的后台处理程序方法,以便它不再处于前台。

如果您想要检查应用程序终止/从最近任务中杀死后,则运行应用程序在发布模式下。这样就可以正常工作。

再次感谢所有人。


1
另一种方法是重新打开应用程序并关闭它,这样它就会像终止的应用程序一样工作。 - A.K.J.94

0
我需要在通知的服务器端主体下方添加以下行:"click_action": "FLUTTER_NOTIFICATION_CLICK"。而 postman 的 json 如下: { "to": "foP947GMRmuin1N********************", "priority": "high", "notification": { "title": "Sakib sent a offer", "body": "An electric bike used 2 years", "android_channel_id": "Messages", "count": 10, "notification_count": 12, "badge": 12, "color": "#eeeeee" }, "data": { "click_action": "FLUTTER_NOTIFICATION_CLICK", "type": "msj", "id": "1" } } 然后在您的清单文件中添加以下代码: <intent-filter> <action android:name="FLUTTER_NOTIFICATION_CLICK" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接