React Native: обрабатывать тихое push-уведомление

Хотя есть много хороших объяснений выше, я пропускаю практический способ разделения шаблонов на заголовок и тело. Моя главная задача - избегать перекомпиляции всех пользователей шаблонов, когда я меняю свое определение. Все экземпляры шаблонов в корпусе шаблона не являются жизнеспособным решением для меня, поскольку автор шаблона может не знать всех, если его использование и пользователь шаблона могут не иметь права его модифицировать. Я принял следующий подход, который также работает и для более старых компиляторов (gcc 4.3.4, aCC A.03.13).

Для каждого использования шаблона в его собственном файле заголовка (сгенерированном из модели UML) имеется typedef, , Его тело содержит экземпляр (который заканчивается в библиотеке, которая связана в конце). Каждый пользователь шаблона включает этот файл заголовка и использует typedef.

Схематический пример:

MyTemplate.h:

#ifndef MyTemplate_h
#define MyTemplate_h 1

template <class T>
class MyTemplate
{
public:
  MyTemplate(const T& rt);
  void dump();
  T t;
};

#endif

MyTemplate.cpp:

#include "MyTemplate.h"
#include <iostream>

template <class T>
MyTemplate<T>::MyTemplate(const T& rt)
: t(rt)
{
}

template <class T>
void MyTemplate<T>::dump()
{
  cerr << t << endl;
}

MyInstantiatedTemplate.h:

#ifndef MyInstantiatedTemplate_h
#define MyInstantiatedTemplate_h 1
#include "MyTemplate.h"

typedef MyTemplate< int > MyInstantiatedTemplate;

#endif

MyInstantiatedTemplate.cpp:

#include "MyTemplate.cpp"

template class MyTemplate< int >;

main.cpp:

#include "MyInstantiatedTemplate.h"

int main()
{
  MyInstantiatedTemplate m(100);
  m.dump();
  return 0;
}

Таким образом, нужно будет перекомпилировать только экземпляры шаблонов, не всех пользователей шаблонов (и зависимостей).

2
задан iori24 16 January 2019 в 10:49
поделиться

1 ответ

Вам не нужны дополнительные пакеты, такие как предложенные в других ответах. Используйте RNFirebase.io, вы можете легко справиться с этим.

Если вы получаете уведомление, если приложение находится в фоновом режиме, вы должны обработать его самостоятельно, чтобы отобразить это уведомление. В качестве примера см. Мой метод init для Push-уведомлений.

  import firebase from 'react-native-firebase';
  const notifications = firebase.notifications();
  ....
  notifications.onNotification((notif) => {
    notif.android.setChannelId('app-infos');
    notifications.displayNotification(notif);
  });

Вы делаете это с displayNotification. Но убедитесь, что вы установили канал уведомлений перед вызовом, потому что иначе он не будет работать на> = Android 8.0

BTW : Убедитесь, что вы полностью настроить Firebase и предоставить все необходимые разрешения, чтобы иметь возможность прослушивать уведомления, если приложение закрыто или в фоновом режиме. ( https://rnfirebase.io/docs/v5.xx/notifications/android )

Приложение

Я добавляю это как пример, чтобы показать, как я Реализовал firebase -tification-stuff как крошечную библиотеку (удалите лишний материал, если он вам не нужен):

import firebase from 'react-native-firebase';
import { saveNotificationToken } from 'app/actions/firebase';
import reduxStore from './reduxStore';
import NavigationService from './NavigationService';

const messaging = firebase.messaging();
const notifications = firebase.notifications();
const crashlytics = firebase.crashlytics();

function registerNotifChannels() {
  try {
    // Notification-Channels is a must-have for Android >= 8
    const channel = new firebase.notifications.Android.Channel(
      'app-infos',
      'App Infos',
      firebase.notifications.Android.Importance.Max,
    ).setDescription('General Information');

    notifications.android.createChannel(channel);
  } catch (error) {
    crashlytics.log(`Error while creating notification-channel \n ${error}`);
  }
}

// This is the Promise object that we use to initialise the push
// notifications. It will resolve when the token was successfully retrieved. The
// token is returned as the value of the Promise.
const initPushNotifs = new Promise(async (resolve, reject) => {
  try {
    const isPermitted = await messaging.hasPermission();

    if (isPermitted) {
      registerNotifChannels();

      try {
        const token = await messaging.getToken();
        if (token) {
          resolve(token);
        }
      } catch (error) {
        crashlytics.log(`Error: failed to get notification-token \n ${error}`);
      }
    }
  } catch (error) {
    crashlytics.log(`Error while checking notification-permission\n ${error}`);
  }

  // If we get this far then there was no token available (or something went
  // wrong trying to get it)
  reject();
});

function init() {
  // Initialise the push notifications, then save the token when/if it's available
  initPushNotifs.then(token => reduxStore.dispatch(saveNotificationToken(token)));

  // Save the (new) token whenever it changes
  messaging.onTokenRefresh(token => reduxStore.dispatch(saveNotificationToken(token)));

  notifications.onNotification((notif) => {
    notif.android.setChannelId('app-infos');
    notifications.displayNotification(notif);
  });

  notifications.onNotificationOpened((notif) => {
    const { notification: { _data: { chatroom: chatRoomId } } = {} } = notif;

    if (chatRoomId) {
      NavigationService.navigate('ChatRoom', { chatRoomId });
    }
  });
}

export default {
  init,
};

При этом перейдите только к своему индексу. js-файл (или ваш корневой файл для вашего приложения, как бы он ни назывался) и вызовите метод init-Metod:

...
import LPFirebase from 'lib/LPFirebase';

LPFirebase.init();
0
ответ дан suther 16 January 2019 в 10:49
поделиться
Другие вопросы по тегам:

Похожие вопросы: