使用react-native-firebase

时间:2018-10-11 05:32:41

标签: react-native android-notifications android-8.0-oreo react-native-firebase

我无法仅在Android 8的Foreground中获得通知。也无法控制后台通知。 但是在低于8的Android版本上,可以很好地使用当前实现。

已执行的步骤:-

  1. 将5.0.0版react-native-firebase插件安装到应用程序中。
  2. 在firebase控制台上创建项目,并将google_service.json文件添加到android / app文件夹中。
  3. 在AndroidManifest中添加了以下代码:-
     <service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
      <intent-filter>
          <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
    </service>
    <service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService>
      <intent-filter>
          <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
      </intent-filter>
    </service>
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService"/>

   <receiver android:name="io.invertase.firebase.notifications.RNFirebaseNotificationReceiver"/>
   <receiver android:enabled="true" android:exported="true" android:name="io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver">
      <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED"/>
          <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
          <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
          <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
   </receiver>
   <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@mipmap/ic_launcher"/>
   <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="test_app"/>
  1. 在App.js页面上添加了以下函数,并在componentDidMountMethod()中调用:-
performNotificationOperations(){
  this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
    console.log("Message",message);
    alert("Notification Message Arrived");
    if(this.state.isLogin){
      const notification = new firebase.notifications.Notification()
                        .setNotificationId(message.messageId)
                        .setTitle(message.data.show_name)
                        .setBody(message.data.description)
                        .setData(message.data)
                        .android.setChannelId('test_app')
                        .android.setBigPicture(message.data.showImage)
                        .android.setPriority(firebase.notifications.Android.Priority.High);
      firebase.notifications().displayNotification(notification).catch(err => alert("Error On Message"));
    }
  });
  this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
    console.log("Notification=>",notification);
    alert("Notification Arrived");
    if(this.state.isLogin){
      notification.android.setChannelId('test_app')
      notification.android.setBigPicture(notification._data.showImage);
      notification.android.setPriority(firebase.notifications.Android.Priority.High)
      firebase.notifications().displayNotification(notification).catch(err => alert("Error On Notification"));
    }
  });
  this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
    console.log(notificationOpen,"Opened listener");
    console.log(notificationOpen.notification._data.type,"notificationOpen");
    firebase.notifications().removeDeliveredNotification(notificationOpen.notification._notificationId)
    if(this.state.isLogin){
      if(notificationOpen.notification._data.type==='show'){
        Navigate.forward('myshowdetails', this._navigator, {show:notificationOpen.notification._data});
      }else if(notificationOpen.notification._data.type==='episode'){
        this.playEpisode(notificationOpen.notification._data.episodeToken);
        Navigate.forward('myshowdetails', this._navigator, {show:notificationOpen.notification._data});
      }
    }
  });
  firebase.notifications().getInitialNotification()
  .then((notificationOpen: NotificationOpen) => {
    if (notificationOpen) {
      alert('Initial Notification');
      console.log(notificationOpen,"notificationOpen");
      console.log(notificationOpen.notification._data.type,"notificationOpen");
      firebase.notifications().removeDeliveredNotification(notificationOpen.notification._notificationId)
      if(this.state.isLogin){
        alert('IS LOGIN TRUE');
        if(notificationOpen.notification._data.type==='show'){
          Navigate.forward('showdetails', this._navigator, {show:notificationOpen.notification._data});
        }else if(notificationOpen.notification._data.type==='episode'){
          this.playEpisode(notificationOpen.notification._data.episodeToken);
          Navigate.forward('showdetails', this._navigator, {show:notificationOpen.notification._data});
        }
      }
    }
  });
  firebase.messaging().getToken().then(token => {
    console.log("GCM Token====>>>>>>>>",token);
    Global.GCM_TOKEN=token;
    // alert(token);
    if(Global.IS_USER_LOGIN){
      Util.saveFCMToken(token);
    }
  });
}
  • 添加了bgMessage.js文件以处理数据消息并使用AppRegistery注册了Headless JS服务。
    // @flow
import firebase from 'react-native-firebase';
// Optional flow type
import type { RemoteMessage } from 'react-native-firebase';
import type { Notification,NotificationOpen} from 'react-native-firebase';

export default async (message: RemoteMessage) => {
    // handle your message
    // console.log("Message=>",message);
    alert("Message Arrived");
    const notification = new firebase.notifications.Notification()
                      .setNotificationId(message.messageId)
                      .setTitle(message.data.show_name)
                      .setBody(message.data.description)
                      .setData(message.data)
                      .android.setChannelId('podpitara_app')
                      .android.setBigPicture(message.data.showImage)
                      .android.setPriority(firebase.notifications.Android.Priority.High);
    firebase.notifications().displayNotification(notification).catch(err => alert("Error in Background"));
    return Promise.resolve();
}
  • 无头JS服务呼叫:-
  

AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage',()=>   bgMessaging);

  • 其他信息:-
  

平台-Android

     

node-version-v8.6.0

     

本机-0.57.0

     

react-native-firebase-0.5.0

  • 面临的问题

    1. 仅在Android 8中无法在Foreground中接收通知。

    2. 在处于后台/最小化状态的情况下,希望以大图显示通知,但无法从我可以处理显示通知的位置获得控制权。

    3. 在调试模式下,应用程序在操作时会在通知托盘中显示图像,但是在释放时,其不显示图像。

请让我知道,我做错了。

2 个答案:

答案 0 :(得分:4)

让它正常工作。

这是因为从Android 8开始,您需要创建一个频道

// Build a channel
const channel = new firebase.notifications.Android.Channel('test-channel', 'Test Channel', firebase.notifications.Android.Importance.Max)
  .setDescription('My apps test channel');

// Create the channel
firebase.notifications().android.createChannel(channel);

https://rnfirebase.io/docs/v4.2.x/notifications/android-channels

我只是在使用

android.setChannelId(message.data.channelId)

现在它显示在应用程序处于前台时。

我的全部功能就是这样

const newNotification = new firebase.notifications.Notification()
            .android.setChannelId(message.data.channelId)
            .setNotificationId(message.messageId)
            .setTitle(message.data.title)
            .setBody(message.data.body)
            .setSound("default")
            .setData(message.Data)
            .android.setAutoCancel(true)
            .android.setSmallIcon('ic_notification')
            .android.setCategory(firebase.notifications.Android.Category.Alarm)

    // Build a channel
    const channelId = new firebase.notifications.Android.Channel(message.data.channelId, channelName, firebase.notifications.Android.Importance.Max);

    // Create the channel
    firebase.notifications().android.createChannel(channelId);
    firebase.notifications().displayNotification(newNotification)

希望这对您有帮助

答案 1 :(得分:0)

这对我有用

componentDidMount()
    {     
    const channel = new firebase.notifications.Android.Channel(
            'channelId',
            'Channel Name',
            firebase.notifications.Android.Importance.Max
          ).setDescription('A natural description of the channel');
          firebase.notifications().android.createChannel(channel);

          this.notificationListener = firebase.notifications().onNotification((notification) => {
            if (Platform.OS === 'android') {

              const localNotification = new firebase.notifications.Notification()
                .setNotificationId(notification.notificationId)
                .setTitle(notification.title)
                .setSubtitle(notification.subtitle)
                .setBody(notification.body)
                .setData(notification.data)
                .android.setSmallIcon("app_icon_name") // use mipmap icon name(have not tried drawable icon)
                .android.setChannelId('channelId') 

                .android.setColor('#ffffff') // you can set a color here
                .android.setPriority(firebase.notifications.Android.Priority.High);

              firebase.notifications()
                .displayNotification(localNotification)
                .catch(err => console.error(err));

            }   });
    }