首页 > 解决方案 > 当应用程序不在前台时访问 React Native Firebase 远程输入通知Open.results

问题描述

在使用 react native firebase 构建通知并添加远程输入和操作后,当应用程序不在前台或屏幕上时,用户输入不会控制台日志。此时,notificationOpen.results 默认为未定义,否则在用户单击发送后会填充用户响应。下面是添加远程输入和监听响应的代码。

export const backgroundMessageListener = async (message) => {
  console.log(message);
  const { data } = message;
  const notification = new firebase.notifications.Notification()
  .setTitle(data.title)
  .setBody(data.body)
  .setSound('default')
  .android.setSmallIcon('notification')
  .android.setColor(colors.primary.normal)
  .android.setAutoCancel(true)
  .android.setLargeIcon(data.icon)
  .android.setChannelId(data.channel)
  .android.setPriority(firebase.notifications.Android.Priority.Max);

  if (!notification.android.channelId) {
    notification.android.setChannelId('misc_channel');
  } else {
    // Build an action
    const action = new firebase.notifications.Android.Action('reply', 'check-mark', `Reply to ${notification.title}`);
    action.setShowUserInterface(false);

    // Build a remote input
    const remoteInput = new firebase.notifications.Android.RemoteInput('input')
    .setLabel('Reply')
    .setAllowFreeFormInput(true);

    // Add the remote input to the action
    action.addRemoteInput(remoteInput);

    // Add the action to the notification
    notification.android.addAction(action);
  }

  // display the notification
  firebase.notifications().displayNotification(notification);

  return Promise.resolve();
};

export const backgroundActionHandler = async (notificationOpen) => {
  if (notificationOpen.action === 'reply') {
    console.log(notificationOpen);
  }
  return Promise.resolve();
};

标签: react-nativefirebase-cloud-messagingandroid-notificationsreact-native-android

解决方案


我已经尝试了以下操作及其工作。但是您需要确保仅发送数据有效负载。

  1. 将此添加到您的 android 清单 xml

 <receiver android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionReceiver" android:exported="true">
        <intent-filter>
            <action android:name="io.invertase.firebase.notifications.BackgroundAction"/>
        </intent-filter>
      </receiver>
      <service android:name="io.invertase.firebase.notifications.RNFirebaseBackgroundNotificationActionsService"/>

  1. 将此文件添加到名为 backgroundMessaging 的 src 文件夹中

import firebase from 'react-native-firebase';
const channelId = 'app-local-notifications';

export const backgroundMessageListener = async message => {
  const channel = new firebase.notifications.Android.Channel(
    channelId,
    'Local Interactive Notifications',
    firebase.notifications.Android.Importance.Max,
  ).setDescription('Local Interactive Notifications');
  firebase.notifications().android.createChannel(channel);

  const localNotification = new firebase.notifications.Notification({
    sound: 'default', //important
  })
    .setNotificationId(message.messageId)
    .setTitle(message.data.title)
    .setBody(message.data.body)
    .android.setChannelId(channelId) //important
    .android.setSmallIcon('ic_launcher')
    .android.setPriority(firebase.notifications.Android.Priority.High); //important

  const action = new firebase.notifications.Android.Action(
    'reply',
    'ic_launcher',
    'Reply',
  );
  action.setShowUserInterface(false);

  const remoteInput = new firebase.notifications.Android.RemoteInput(
    'inputText',
  );
  remoteInput.setLabel('Message');
  action.addRemoteInput(remoteInput);

  localNotification.android.addAction(action);
  firebase
    .notifications()
    .displayNotification(localNotification)
    .catch(err => console.log(err)); //important
};

export const backgroundActionHandler = async notificationOpen => {
  if (notificationOpen && notificationOpen.notification) {
    const action = notificationOpen.action;
    const notificationId = notificationOpen.notification.notificationId;
    if (action === 'reply') {
      console.log(notificationOpen);
    } else {
      console.log('unsupported action', action);
    }
    // hide the notification instead of Promise.resolve()
    firebase.notifications().removeDeliveredNotification(notificationId); //important
  }
};

  1. 将此添加到您的根项目中的 index.js

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => backgroundMessageListener)
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundNotificationAction', () => backgroundActionHandler);

  1. 这将发送到管理脚本以仅发送数据有效负载

async function sendPushNotification(message) {
try {
    await admin.messaging().sendToDevice(
        ['eTlozrPo49U:APA91bEPJhpZPN4rVUjJL93y9PxN5DFKH198RJOSPZ9qHgBenmtcuMIPOmUTZGuFEGc07OxGkgh4OpSyggOr13ud3W9Ipokp61VayZ29sucTuyjHCjDGlNCfTbliwKiN0uDBjpklpOR0'],
        {
            data: {
                title: 'a',
                body: 'a',
                navigation: 'CreateOrderLandingScreen'
            },
        },
        {
            // Required for background/quit data-only messages on iOS
            contentAvailable: true,
            // Required for background/quit data-only messages on Android
            priority: 'high',
        },
    );

    console.log('A');

}catch(e) {
    console.log('Gagal mengirim pesan');
}

}


推荐阅读