| Выберите платформу: | iOS+ Android Web Flutter Unity C++ |
В этом руководстве описано, как начать работу с Firebase Cloud Messaging в ваших клиентских приложениях на C++, чтобы вы могли надежно отправлять сообщения.
To write your cross-platform Firebase Cloud Messaging client app with C++, use the Firebase Cloud Messaging API. The C++ SDK works for both Android and Apple platforms, with some additional setup required for each platform. To learn more about how the C++ SDK for iOS and Android works with FCM , see Understand Firebase for C++ .
Настройте Firebase и SDK FCM
Android
Если вы еще этого не сделали, добавьте Firebase в свой проект на C++ .
В прилагаемых инструкциях по настройке ознакомьтесь с требованиями к устройству и приложению для использования Firebase C++ SDK, включая рекомендацию использовать CMake для сборки вашего приложения.
В файле
build.gradleна уровне проекта обязательно укажите репозиторий Maven от Google в разделахbuildscriptиallprojects.
Создайте объект Firebase App, передав ему среду JNI и Activity:
app = ::firebase::App::Create(::firebase::AppOptions(), jni_env, activity);
Определите класс, реализующий интерфейс
firebase::messaging::Listener.Инициализируйте FCM , передав в качестве параметров приложение и созданный слушатель:
::firebase::messaging::Initialize(app, listener);
Apps that rely on the Google Play services SDK should check the device for a compatible Google Play services APK before accessing the features. To learn more, refer to Check for Google Play services APK .
iOS+
- Если вы еще этого не сделали, добавьте Firebase в свой проект C++ . Затем, чтобы настроить проект для FCM :
- В файл Podfile вашего проекта добавьте зависимость FCM:
pod 'FirebaseMessaging'
- Перетащите фреймворки
firebase.frameworkиfirebase_messaging.frameworkиз Firebase C++ SDK в свой проект Xcode.
- В файл Podfile вашего проекта добавьте зависимость FCM:
Загрузите свой ключ аутентификации APNs в Firebase. Если у вас еще нет ключа аутентификации APNs, обязательно создайте его в Центре разработчиков Apple .
- В консоли Firebase перейдите по адресу
> Общие . Затем перейдите на вкладку «Облачные сообщения» . - В разделе «Ключ аутентификации APNs» в настройках приложения iOS нажмите «Загрузить» , чтобы загрузить ключ аутентификации для разработки, ключ аутентификации для производства или оба. Требуется как минимум один ключ.
- Перейдите к месту, где вы сохранили свой ключ, выберите его и нажмите «Открыть» . Добавьте идентификатор ключа (доступен в Центре для разработчиков Apple ) и нажмите «Загрузить» .
- В консоли Firebase перейдите по адресу
Настройте свой проект Xcode, чтобы включить push-уведомления:
- Выберите проект в разделе «Навигатор» .
- Выберите целевой проект в области редактора .
В редакторе выберите вкладку «Общие» .
- Прокрутите страницу до раздела «Связанные фреймворки и библиотеки» , затем нажмите кнопку «+» , чтобы добавить фреймворки.
В появившемся окне прокрутите до раздела UserNotifications.framework , щелкните по записи, а затем нажмите «Добавить» .
Этот фреймворк появляется только в Xcode версии 8 и более поздних версиях и необходим для работы этой библиотеки.
В редакторе выберите вкладку «Возможности» .
- Включите push-уведомления .
- Прокрутите до пункта «Режимы фона» , затем переключите его в положение «Вкл.» .
- В разделе «Фоновые режимы» выберите «Удаленные уведомления» .
Создайте объект Firebase App:
app = ::firebase::App::Create(::firebase::AppOptions());
Определите класс, реализующий интерфейс
firebase::messaging::Listener.Инициализируйте Firebase Cloud Messaging, передав в качестве параметров приложение и созданный слушатель:
::firebase::messaging::Initialize(app, listener);
Получите доступ к идентификатору установки Firebase.
Включите регистрацию с использованием идентификатора установки Firebase.
Чтобы включить регистрацию экземпляра вашего приложения в FCM с использованием идентификатора установки Firebase (FID) , необходимо сначала включить FID в конфигурации вашего приложения как для платформ Android, так и для Apple:
Android
Добавьте следующий элемент <meta-data> внутрь элемента <application> в вашем AndroidManifest.xml :
<meta-data android:name="firebase_messaging_installation_id_enabled" android:value="true" />
Быстрый
Добавьте ключ FirebaseMessagingInstallationIdEnabled в файл Info.plist и установите для него значение YES :
FirebaseMessagingInstallationIdEnabled = YES
Реализуйте обработчик события onRegistrationReceived
When initializing the Firebase Cloud Messaging library, it registers the client app instance for receiving messages using a Firebase Installation ID (FID) . The app will receive the FID with the OnRegistrationReceived callback, which should be defined in your firebase::messaging::Listener implementation:
class MyListener : public firebase::messaging::Listener { public: void OnRegistrationReceived(const char* installation_id) override { LogMessage("Received Firebase Installation ID: %s", installation_id); // TODO: Send the Firebase Installation ID (FID) to your app server to // target this device for messages. } };
Если вы хотите выбрать конкретный экземпляр приложения, отправьте FID на сервер вашего приложения и сохраните его, используя предпочитаемый вами метод.
При отключенной автоматической инициализации регистрация выполняется вручную.
Также можно вручную запустить регистрацию в FCM во время выполнения, используя Register() :
// Manually register with FCM firebase::Future<void> register_future = firebase::messaging::Register(); register_future.OnCompletion([](const firebase::Future<void>& future) { if (future.status() == firebase::kFutureStatusComplete && future.error() == 0) { // Note: The registered Firebase Installation ID is delivered to the // OnRegistrationReceived callback. LogMessage("Registered with FCM"); } });
Для доступа к регистрационному токену FCM (устаревший)
Upon initializing the Firebase Cloud Messaging library, a registration token is requested for the client app instance. The app will receive the token with the OnTokenReceived callback, which should be defined in the class that implements firebase::messaging::Listener .
Если вы хотите применить изменения именно к этому экземпляру приложения, вам потребуется доступ к этому токену.
Примечание о доставке сообщений на Android.
When the app is not running at all and a user taps on a notification, the message is not, by default, routed through FCM 's built in callbacks. In this case, message payloads are received through an Intent used to start the application. To have FCM forward these incoming messages to the C++ library callback, you need to override the method onNewIntent in your Activity and pass the Intent to the MessageForwardingService .
import com.google.firebase.messaging.MessageForwardingService; class MyActivity extends Activity { private static final String TAG = "MyActvity"; @Override protected void onNewIntent(Intent intent) { Log.d(TAG, "A message was sent to this app while it was in the background."); Intent message = new Intent(this, MessageForwardingService.class); message.setAction(MessageForwardingService.ACTION_REMOTE_INTENT); message.putExtras(intent); message.setData(intent.getData()); // For older versions of Firebase C++ SDK (< 7.1.0), use `startService`. // startService(message); MessageForwardingService.enqueueWork(this, message); } }
Messages received while the app is in the background have the content of their notification field used to populate the system tray notification, but that notification content won't be communicated to FCM . That is, Message::notification will be a null.
В итоге:
| Состояние приложения | Уведомление | Данные | Оба |
|---|---|---|---|
| Передний план | OnMessageReceived | OnMessageReceived | OnMessageReceived |
| Фон | Системный трей | OnMessageReceived | Уведомление: системный трей Данные: в дополнительных материалах, отражающих замысел. |
Пользовательская обработка сообщений в Android
By default, notifications sent to the app are passed to ::firebase::messaging::Listener::OnMessageReceived , but in some cases you may want to override the default behavior. To do this on Android you will need to write custom classes that extend com.google.firebase.messaging.cpp.ListenerService as well as update your project's AndroidManifest.xml .
Переопределите методы ListenerService
The ListenerService is the Java class that intercepts incoming messages sent to the app and routes them to the C++ library. When the app is in the foreground (or when the app is in the background and it receives a data-only payload), messages will pass through one of the callbacks provided on this class. To add custom behavior to the message handling, you will need to extend FCM 's default ListenerService :
import com.google.firebase.messaging.cpp.ListenerService; class MyListenerService extends ListenerService {
Переопределив метод ListenerService.onMessageReceived , вы можете выполнять действия на основе полученного объекта RemoteMessage и получать данные сообщения:
@Override public void onMessageReceived(RemoteMessage message) { Log.d(TAG, "A message has been received."); // Do additional logic... super.onMessageReceived(message); }
ListenerService также есть несколько других методов, которые используются реже. Их тоже можно переопределить; для получения дополнительной информации см. справочник FirebaseMessagingService .
@Override public void onDeletedMessages() { Log.d(TAG, "Messages have been deleted on the server."); // Do additional logic... super.onDeletedMessages(); } @Override public void onMessageSent(String messageId) { Log.d(TAG, "An outgoing message has been sent."); // Do additional logic... super.onMessageSent(messageId); } @Override public void onSendError(String messageId, Exception exception) { Log.d(TAG, "An outgoing message encountered an error."); // Do additional logic... super.onSendError(messageId, exception); }
Обновите файл AndroidManifest.xml
Once your custom classes have been written, they must be included in the AndroidManifest.xml to take effect. Make sure that the manifest includes the merge tools by declaring the appropriate attribute inside the <manifest> tag, like so:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.firebase.messaging.cpp.samples" xmlns:tools="http://schemas.android.com/tools">
In the firebase_messaging_cpp.aar archive there is an AndroidManifest.xml file which declares FCM 's default ListenerService . This manifest is normally merged with the project specific manifest which is how the ListenerService is able to run. This ListenerService needs to replaced with the custom listener service. That is accomplished by removing the default ListenerService and adding the custom Service, which can be done with the following lines your projects AndroidManifest.xml file:
<service android:name="com.google.firebase.messaging.cpp.ListenerService" tools:node="remove" />
<service android:name="com.google.firebase.messaging.cpp.samples.MyListenerService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service>
В новых версиях Firebase C++ SDK (начиная с 7.1.0) используется JobIntentService , что требует дополнительных изменений в файле AndroidManifest.xml .
<service android:name="com.google.firebase.messaging.MessageForwardingService" android:permission="android.permission.BIND_JOB_SERVICE" android:exported="false" > </service>
Предотвратить автоматическую инициализацию
FCM generates a registration token for app instance targeting. When a token is generated, the library uploads the identifier and configuration data to Firebase. If you want to get an explicit opt-in before using the token, you can prevent generation at configure time by disabling FCM (and on Android, Analytics). To do this, add a metadata value to your Info.plist (not your GoogleService-Info.plist ) on Apple platforms, or your AndroidManifest.xml on Android:
Android
<?xml version="1.0" encoding="utf-8"?> <application> <meta-data android:name="firebase_messaging_auto_init_enabled" android:value="false" /> <meta-data android:name="firebase_analytics_collection_enabled" android:value="false" /> </application>
Быстрый
FirebaseMessagingAutoInitEnabled = NO
Для повторного включения FCM можно выполнить вызов во время выполнения:
::firebase::messaging::SetRegistrationOnInitEnabled(true);
После установки это значение сохраняется при перезапуске приложения.
Сообщения с прямыми ссылками на Android
FCM allows messages to be sent containing a deep link into your app. To receive messages that contain a deep link, you must add a new intent filter to the activity that handles deep links for your app. The intent filter should catch deep links of your domain. If your messages don't contain a deep link, this configuration is not necessary. In AndroidManifest.xml:
<intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:host="CHANGE_THIS_DOMAIN.example.com" android:scheme="http"/> <data android:host="CHANGE_THIS_DOMAIN.example.com" android:scheme="https"/> </intent-filter>
Также можно указать подстановочный знак, чтобы сделать фильтр намерений более гибким. Например:
<intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:host="*.example.com" android:scheme="http"/> <data android:host="*.example.com" android:scheme="https"/> </intent-filter>
Когда пользователи нажимают на уведомление, содержащее ссылку на указанную вами схему и хост, ваше приложение запускает активность с этим фильтром намерений для обработки ссылки.
Следующие шаги
После завершения этапов настройки, вот несколько вариантов для дальнейшей работы с FCM для C++:
- Отправляйте сообщения на устройства
- Получение сообщений в приложении на C++
- Отправляйте сообщения по темам