Flutter推送通知仅在应用程序处于后台时工作

10
我的问题涉及使用Flutter和firebase_messaging插件进行推送通知。
问题:
我已将firebase_messaging插件集成到我的Flutter应用程序中以进行推送通知。 我可以保证,就我所知,设置是正确的,因为我正在接收推送通知。 问题出现在仅当我的应用程序在后台运行(如最小化但仍在系统内存中)时才会接收到推送。 当应用程序在前台或被杀死时,将无法接收到推送
为了提供我尝试过的解决方案,我无法弄清楚实际上需要做什么。
我已经按照教程进行了操作,并采取了每一步来克服问题,但都没有成功。
我正在使用NodeJS处理firebase-admin和serviceaccountkey文件,因为我需要从我的数据库中获取device_tokens。
 const firebase = require('firebase-admin');
 const serviceAccount = require('../controller/firebase/serviceAccountKey.json');
 firebase.initializeApp({
  credential: firebase.credential.cert(serviceAccount)
 });

 //Function to actually implement the push
 const pushNotificationInitiatorSubscription = (resultValue) => {
 let devicesTokenString = resultValue[0]['device_token'];
 const firebaseToken = devicesTokenString;
 const payLoad = {
   notification: {
   title: 'New Subscription',
   body: 'You have a new subscription to your material ' + resultValue[0]['course_name']
 }
};
const option = {
 priority: 'high'
};

firebase.messaging().sendToDevice(firebaseToken, payLoad, option).then(success => {
  // console.log(success.results[0]['error']);
  // console.log(success.results[1]['error']);
  // console.log(success);
}).catch(err => {
 console.log(err);
})

Flutter

import 'package:firebase_messaging/firebase_messaging.dart';

class FirebaseCloudMessage {
 static FirebaseCloudMessage _instance = new FirebaseCloudMessage.internal();
 FirebaseCloudMessage.internal();
 factory FirebaseCloudMessage() => _instance;

 final FirebaseMessaging _firebaseMessaging = new FirebaseMessaging();

 configureFirebaseListeners() {
  print('Here');
  _firebaseMessaging.configure(
    onMessage: (Map<String, dynamic> message) async {
  print("Message $message");
  // return message;
}, onLaunch: (Map<String, dynamic> message) async {
  print("Message $message");
  // return message;
}, onResume: (Map<String, dynamic> message) async {
  print("Message $message");
  // return message;
});
}
}

需要帮助。谢谢

1个回答

14

这是目前从Firebase通知服务接收到的通知的默认行为。如果您想在应用程序在前台运行时显示通知,您需要手动编写代码。

以下是使用flutter_local_notifications包在Flutter中显示通知的演示。

注意:这只是使用flutter_local_notification包在Flutter中显示通知的非常基本的例子。您可以进行很多配置。有关详细说明,请访问此包的主页或阅读这篇非常好的medium文章

步骤1:在pubspec.yaml中安装flutter_local_notifications包。

步骤2:在initState()中初始化FlutterLocalNotifications:

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

    var initializationSettingsAndroid =
        new AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializationSettingsIOS = new IOSInitializationSettings();
    var initializationSettings = new InitializationSettings(
        initializationSettingsAndroid, initializationSettingsIOS);

    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: onSelectNotification);
  }

第三步: 创建一个函数来处理通知的点击事件。当用户点击通知时,将调用此函数。

Future<dynamic> onSelectNotification(String payload) async {
    /*Do whatever you want to do on notification click. In this case, I'll show an alert dialog*/
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: Text(payload),
        content: Text("Payload: $payload"),
      ),
    );
  }

第四步:编写一个函数来显示通知:

Future<void> _showNotification(
    int notificationId,
    String notificationTitle,
    String notificationContent,
    String payload, {
    String channelId = '1234',
    String channelTitle = 'Android Channel',
    String channelDescription = 'Default Android Channel for notifications',
    Priority notificationPriority = Priority.High,
    Importance notificationImportance = Importance.Max,
  }) async {
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
      channelId,
      channelTitle,
      channelDescription,
      playSound: false,
      importance: notificationImportance,
      priority: notificationPriority,
    );
    var iOSPlatformChannelSpecifics =
        new IOSNotificationDetails(presentSound: false);
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
      notificationId,
      notificationTitle,
      notificationContent,
      platformChannelSpecifics,
      payload: payload,
    );
  }

第五步:调用_showNotification()函数:

_firebaseMessaging.configure(
    onMessage: (Map<String, dynamic> message) async {
        //print("Message $message");
        _showNotification(1234, "GET title FROM message OBJECT", "GET description FROM message OBJECT", "GET PAYLOAD FROM message OBJECT");
        return;
    }
}

完成后,即使您的应用在前台运行,也可以显示通知。希望这会有所帮助。


感谢@Avishek的回复。我想知道firebase_messaging是否具有默认行为?因为我在许多教程中都看到了前台和应用程序关闭时收到通知的情况。我也对切换到新包持怀疑态度。希望能获得有关firbase_messaging插件的帮助。 - Subhajit Syam Choudhury
@Subhajit Syam Choudhury 是的,这是 Firebase Messaging for Flutter 的默认行为。当应用程序处于前台时不会显示通知。您必须手动编写代码以显示通知。如果您不想使用 flutter_local_notifications 包,则可以简单地使用 Alert Dialog 来显示通知(而不是在状态栏中)。要在状态栏中显示通知,您必须使用 flutter_local_notification 或任何其他类似的包。 - Abhishek Diwakar
如果您对使用其他软件包持怀疑态度,您可以使用方法通道来访问核心Android功能,并从您的Android代码中显示通知。 - Abhishek Diwakar
好的,谢谢@Abhishek。我会尝试你的建议。同时,我将把你的答案标记为正确答案,以供任何遇到类似问题的人参考。 - Subhajit Syam Choudhury
@AbhishekDiwakar 嗨,我试过这个方法,它可以工作,但我的使用情况有些不同。我希望通知弹出窗口一直停留在屏幕上,直到用户关闭它。目前,弹出窗口会在几秒钟后消失,而通知仍然停留在通知栏中。但我希望弹出窗口至少停留一分钟或更长时间,或者直到用户关闭它。这可能吗? - Md. Kamrul Amin
你知道如何在应用程序终止时处理通知的点击吗?我尝试使用getInitialMessage,但它对我不起作用。 - Dipak Ramoliya

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