Невозможно получить уведомление на переднем плане на Android 8 с использованием response-native-firebase - PullRequest
0 голосов
/ 11 октября 2018

Мне не удается получить уведомление в Foreground только на Android 8.Также не удается получить контроль над фоновым уведомлением. Но на версии Android ниже 8 нормально работает с текущей реализацией.

Выполнены следующие шаги: -

  1. Установка плагина реакции-native-firebase версии 5.0.0 в приложение.
  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"/>
Ниже добавлена ​​функция на странице 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 для обработки сообщений данныхи зарегистрированный сервис Headless JS с использованием AppRegistery.
    // @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);

  • Дополнительная информация: -
*Платформа 1051 * - Android

версия узла - v8.6.0

response-native - 0.57.0

response-native-firebase - 0.5.0

  • Проблемы, с которыми сталкиваются

    1. Невозможно получить уведомление на переднем плане только в случае Android 8.

    2. В случае фона / свернутого состояния, я хочу показывать уведомление с большой картинкой, но не могу получить контроль над тем, где я могу обработать отображение уведомления.

    3. В случае режима отладки приложение отображает изображение в трее уведомлений peroperly, но в случае выпуска оно не показывает изображение.

Пожалуйста, дайте мне знать, что я делаю не так.

1 Ответ

0 голосов
/ 06 ноября 2018

Получил это на работу.

Это потому, что из 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)

Надеюсь, это поможет вам

...