Flutter推送通知仅在应用程序处于后台时有效 [英] Flutter push notification is working only when app is in background

查看:639
本文介绍了Flutter推送通知仅在应用程序处于后台时有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My problem is regarding the push notification using Flutter and firebase_messaging plugin

问题:

我已将 firebase_messaging 插件集成到我的Flutter应用中,以进行推送通知. 据我所知,我可以保证在我收到推送通知时,该设置是正确的.仅当我的应用程序在后台运行时(例如,最小化但在系统内存中可用),才收到推送请求. 当应用程序处于前台或被终止时,未收到推送.

I have integrated firebase_messaging plugin to my flutter app for push notification. I can guarantee that the setup is correct to the best of my knowledge as i am receiving push notification. The problem occurs when pushes are received only when my app is running in the background(like minimizing but available in the system memory). Pushes are not received when app is in foreground or is killed.

要提供我尝试过的解决方案,我不知道实际需要完成什么.

To provide a solution on what I have tried, I could not figure out actually needs to be done.

我遵循了有关此问题的教程,并应用了每个步骤来克服该问题,但无济于事.

I have followed tutorials on this and applied every single step to overcome the problem but to no avail.

我正在使用nodeJS来处理firebase-admin和serviceaccountkey文件,因为我需要从数据库中获取device_tokens.

I am using nodeJS to handle the firebase-admin and serviceaccountkey file as I need device_tokens from my DB.

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

我们将不胜感激.谢谢

推荐答案

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

This is the default behavior of notifications received from the firebase notification service currently. You have to manually write code if you wanna show the notification when your app is in the foreground.

这是一个使用 flutter_local_notifications 软件包在通知中显示通知的演示.

Here's a demo of showing notification in flutter using flutter_local_notifications package.

注意:这是一个非常基本的示例,使用 flutter_local_notification

NOTE: This is a really basic example of showing notifications in flutter using flutter_local_notification package. There's a lot you can configure. For a detailed explanation, visit homepage of this package or read this really good medium article

步骤1:在您的pubspec.yaml中安装 flutter_local_notifications 软件包

Step 1: install flutter_local_notifications package in your pubspec.yaml

第2步:在initState()中启动FlutterLocalNotifications:

Step 2: initiate FlutterLocalNotifications in initState():

@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步:创建一个函数来处理通知中的点击事件.当用户点击通知时,将调用此功能.

Step 3: Create a function to handle click events on the notification. This function will be called when a user will tap on the notification.

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步:编写一个显示通知的函数:

Step 4: Write a function to show notification:

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()函数:

Step 5: Call the _showNotification() function:

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

此后,即使您的应用程序位于前台,您也可以显示通知.希望这会很有用.

After this, you will be able to show notification even when your app is in the foreground. Hopefully, this will be useful.

这篇关于Flutter推送通知仅在应用程序处于后台时有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆