English 中文(简体)
使用防火基的碎散通知在从终端服务器发送时不会在地下作业
原标题:Flutter notification using firebase does not work on foreground while sending from node server

我正在使用消防基地信息发送通知。 我创建了一个使用电灯发送通知的APIC,我接待了Cylic免费服务器的APIC。

通知对当地服务器进行罚款,同时直接从消防基地召集。 然而,如果从APIC服务器发出的地面通知上寄来的,则不会奏效。 它是在收到通知的情况下和之后开展工作的,同时也开始在地下收到通知。

我的法典

async function sendPushNotification(qrId, requestData) {
try {
    const users = await findUsersByQrId(qrId);

    if (users.length === 0) {
        return { message:  No user found with the provided qrId  };
    }

    const user = users[0];

    const invalidTokens = [];
    const notificationData = {

        "qrId": requestData.qrId,
        "name": requestData.name,
        "email": requestData.email,
        "phoneNumber": requestData.phoneNumber,
        "location": requestData.location,
        "customMsg": requestData.customMsg,
        "userId": user._id

    }
    console.log("notification data", notificationData);
    const message = createNotificationMessage(notificationData);

    sendNotificationToTokens(message, user.fcmTokens, invalidTokens, user);
    await saveNotificationToDatabase(requestData, user);

    return {
        message:  Notifications Sent ,
        invalidTokens,
    };
  } catch (error) {
    throw new Error( An error occurred );
  }
  }

  // Function to find users by qrId
    async function findUsersByQrId(qrId) {
    const users = await User.find({ qrId });
    return users;
    }

   // Function to create a notification message
  function createNotificationMessage(data) {
    return {
      notification: {
        title: `Notification from ${data.name}`,
        body: data.customMsg || data.location || data.name,
      },
     data: {  //you can send only notification or only data(or include both)
        userId: `${data.userId}`,
       
     },
    android:{
        priority:  high 
    }
  };
 }


// Function to send a notification to multiple FCM tokens
function sendNotificationToTokens(message, tokens, invalidTokens, user) {
FCM.sendToMultipleToken(message, tokens, (err, response) => {
    if (err) {
        console.log("Error code", err.code);
        console.log("Error", err);
        if (err.code ===  messaging/registration-token-not-registered ) {
            console.log("Invalid tokens", fcmToken);
            invalidTokens.push(fcmToken);
        } else {
            throw err;
        }
    } else {
        response.forEach(async element => {
            if (element["response"] === "Error sending message:") {
                invalidTokens.push(element["token"]);
            }
        });
        removeInvalidTokens(user, invalidTokens);

    }
  });
}

我的冲破边法

 class FirebaseNotification {
    FirebaseNotification();

    final _firebaseMessaging = FirebaseMessaging.instance;

    final _androidChannel = const AndroidNotificationChannel(
     high_importance_channel , // id
     High Importance Notifications , // title
    description:
     This channel is used for important notifications. , // description
   importance: Importance.max,
  );

  final _localNotifications = FlutterLocalNotificationsPlugin();

  Future<void> initNotifications() async {
  await _firebaseMessaging.requestPermission();
  initPushNotification();
  initLocalNotifications();
  }

  Future initPushNotification() async {
    await FirebaseMessaging.instance
    .setForegroundNotificationPresentationOptions(
        alert: true, badge: true, sound: true);
    FirebaseMessaging.instance.getInitialMessage().then(handleMessage);
    FirebaseMessaging.onMessageOpenedApp.listen(handleMessage);
    FirebaseMessaging.onBackgroundMessage(handleBackgroundMessage);
    FirebaseMessaging.onMessage.listen((message) {
    final notification = message.notification;
      if (notification == null) return;
       _localNotifications.show(
      notification.hashCode,
      notification.title,
      notification.body,
      NotificationDetails(
          android: AndroidNotificationDetails(
        _androidChannel.id,
        _androidChannel.name,
        channelDescription: _androidChannel.description,
        icon:  @drawable/logo ,
      )),
      payload: jsonEncode(message.toMap()));
  });
  }

  Future initLocalNotifications() async {
    const iOS = DarwinInitializationSettings();
    const android = AndroidInitializationSettings( @drawable/logo );
    const settings = InitializationSettings(
    android: android,
   iOS: iOS,
  );
   await _localNotifications.initialize(settings,
    onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);
  }

 void onDidReceiveNotificationResponse(
   NotificationResponse notificationResponse) async {
  final String? payload = notificationResponse.payload;
  if (notificationResponse.payload != null) {
  final message = RemoteMessage.fromMap(jsonDecode(payload!));
  handleMessage(message);
  final platform =
      _localNotifications.resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>();
  await platform?.createNotificationChannel(_androidChannel);
  }
 }
 }
问题回答
  1. try get new fcmToken to the new device
  2. what s the error of your firebase functions on your console?
  3. it is actual device or emulator ?
  4. did you get permission on your mobile phone ?




相关问题
Port Number for Incoming Apple Push Notifications

What network services, port numbers, outgoing incoming or both, need to be open on a network for an ipod touch to receive Apple Push Notifications? I know the outgoing port number to set when sending ...

Push notifications dialogue

Is there any way I could make the "Would you like to enable push notifications..." dialogue not to come up upon first time application launch but rather on some other action in the application? ...

热门标签