【问题标题】:Flutter push notification is working only when app is in backgroundFlutter 推送通知仅在应用程序处于后台时有效
【发布时间】:2020-10-22 14:10:55
【问题描述】:

我的问题是关于使用 Flutter 和 firebase_messaging 插件的推送通知

问题:

我已将 firebase_messaging 插件集成到我的颤振应用程序中以进行推送通知。 当我收到推送通知时,我可以保证设置是正确的。仅当我的应用程序在后台运行(例如最小化但在系统内存中可用)时才收到推送时出现问题。 当应用处于前台或被杀死时,没有收到推送

为了提供我尝试过的解决方案,我无法弄清楚实际上需要做些什么。

我遵循了这方面的教程并应用了每一个步骤来解决问题,但无济于事。

我正在使用 nodeJS 来处理 firebase-admin 和 serviceaccountkey 文件,因为我需要来自我的数据库的 device_tokens。

NodeJS

 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);
})

颤动

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;
});
}
}

我们将不胜感激。谢谢

【问题讨论】:

    标签: node.js flutter push-notification firebase-cloud-messaging


    【解决方案1】:

    这是当前从 firebase 通知服务接收到的通知的默认行为。如果您想在应用处于前台时显示通知,则必须手动编写代码。

    这是一个使用 flutter_local_notifications 包在颤振中显示通知的演示。

    注意:这是使用flutter_local_notification 包在颤振中显示通知的非常基本的示例。您可以配置很多。详细解释请访问此包的homepage 或阅读此非常好的medium article

    第 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);
      }
    

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

    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"),
          ),
        );
      }
    

    第 4 步:编写一个显示通知的函数:

    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,
        );
      }
    

    第 5 步:调用 _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 是的,这是用于颤振的 firebase 消息传递的默认行为。应用程序在前台时不显示任何通知。您必须手动编写代码来显示通知。如果您不想使用 flutter_local_notifications 包,您可以简单地使用警报对话框来显示通知(不在状态栏中)。要在状态栏中显示通知,您必须使用 flutter_local_notification 或任何其他类似的包。
    • 如果您对使用其他包持怀疑态度,可以使用方法通道访问核心 Android 功能并显示来自您的 Android 代码的通知。
    • 好的,谢谢@Abhishek。我会尝试你的建议。同时,对于任何坚持类似方法的人,我将您的答案标记为正确的答案。
    • @AbhishekDiwakar 嘿,我试过了,但我有一个不同的用例。我希望弹出通知保持在屏幕上,直到用户关闭。目前,弹出窗口会在几秒钟后消失,通知保留在通知托盘内。但我希望弹出窗口至少停留一分钟左右,或者直到用户关闭它。有可能吗?
    猜你喜欢
    • 2018-08-04
    • 2019-02-25
    • 2022-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    相关资源
    最近更新 更多