Начните работу с Firebase Cloud Messaging


В этом кратком руководстве описывается, как настроить Firebase Cloud Messaging в мобильных и веб-клиентских приложениях для надежной отправки сообщений. Сведения о серверных средах см. в разделе «Ваша серверная среда» и FCM .

Настройка клиентского приложения Firebase Cloud Messaging с помощью Unity

Чтобы создать кроссплатформенное клиентское приложение Firebase Cloud Messaging на Unity, используйте API Firebase Cloud Messaging . SDK Unity работает как на Android, так и на Apple, но для каждой платформы требуется дополнительная настройка.

Прежде чем начать

Предпосылки

  • Установите Unity 2021 LTS или более позднюю версию. Поддержка Unity 2020 считается устаревшей и не будет активно поддерживаться после следующего основного релиза. Более ранние версии также могут быть совместимы, но не будут активно поддерживаться.

  • (Только для платформ Apple) Установите следующее:

    • Xcode 13.3.1 или выше
    • CocoaPods 1.12.0 или выше
  • Убедитесь, что ваш проект Unity соответствует следующим требованиям:

    • Для iOS — предназначено для iOS 13 и выше.
    • Для tvOS — предназначено для tvOS 13 и выше
    • Для Android — ориентирован на API уровня 21 (Lollipop) или выше
  • Настройте устройство или используйте эмулятор для запуска вашего проекта Unity.

    • Для iOS или tvOS — настройте физическое устройство для запуска приложения и выполните следующие задачи:

    • Для Androidэмуляторы должны использовать образ эмулятора с Google Play.

Если у вас еще нет проекта Unity и вы просто хотите опробовать продукт Firebase, вы можете загрузить один из наших примеров быстрого старта .

Шаг 1: Создайте проект Firebase

Прежде чем добавить Firebase в свой проект Unity, необходимо создать проект Firebase для подключения к нему. Подробнее о проектах Firebase можно узнать в разделе «Понимание проектов Firebase».

Шаг 2: Зарегистрируйте свое приложение в Firebase

Вы можете зарегистрировать одно или несколько приложений или игр для подключения к вашему проекту Firebase.

  1. Перейдите в консоль Firebase .

  2. В центре страницы обзора проекта щелкните значок Unity ( ), чтобы запустить рабочий процесс настройки.

    Если вы уже добавили приложение в свой проект Firebase, нажмите «Добавить приложение» , чтобы отобразить параметры платформы.

  3. Выберите, какую цель сборки вашего проекта Unity вы хотите зарегистрировать, или вы даже можете зарегистрировать обе цели одновременно.

  4. Введите идентификатор(ы) платформы вашего проекта Unity.

    • Для iOS — введите идентификатор iOS вашего проекта Unity в поле идентификатора пакета iOS .

    • Для Android — введите идентификатор Android вашего проекта Unity в поле имени пакета Android .
      Термины «имя пакета» и «идентификатор приложения» часто используются как взаимозаменяемые.

  5. (Необязательно) Введите псевдонимы, специфичные для платформы вашего проекта Unity.
    Эти псевдонимы являются внутренними, удобными идентификаторами и видны только вам в консоли Firebase .

  6. Нажмите «Зарегистрировать приложение» .

Шаг 3: Добавьте файлы конфигурации Firebase

  1. Получите файлы конфигурации Firebase для вашей платформы в рабочем процессе настройки консоли Firebase .

    • Для iOS — нажмите «Загрузить GoogleService-Info.plist» .

    • Для Android — нажмите «Загрузить google-services.json» .

  2. Откройте окно проекта Unity, затем переместите файл(ы) конфигурации в папку Assets .

  3. Вернитесь в консоль Firebase , в рабочем процессе настройки нажмите кнопку Далее .

Шаг 4: Добавьте Firebase Unity SDK

  1. В консоли Firebase нажмите «Загрузить Firebase Unity SDK» , затем распакуйте SDK в удобное место.

    • Вы можете снова загрузить Firebase Unity SDK в любое время.

    • Firebase Unity SDK не привязан к какой-либо платформе.

  2. В открытом проекте Unity перейдите в раздел Assets > Import Package > Custom Package .

  3. В распакованном SDK выберите поддерживаемые продукты Firebase , которые вы хотите использовать в своем приложении.

    Для оптимальной работы с Firebase Cloud Messaging рекомендуем включить Google Analytics в вашем проекте. Кроме того, в рамках настройки Analytics необходимо добавить пакет Firebase для Analytics в ваше приложение.

    Analytics включена

    • Добавьте пакет Firebase для Google Analytics : FirebaseAnalytics.unitypackage
    • Добавьте пакет для Firebase Cloud Messaging : FirebaseMessaging.unitypackage

    Analytics не включена

    Добавьте пакет для Firebase Cloud Messaging : FirebaseMessaging.unitypackage

  4. В окне Импорт пакета Unity нажмите Импорт .

  5. Вернитесь в консоль Firebase , в рабочем процессе настройки нажмите кнопку Далее .

Шаг 5: Подтвердите требования к версии сервисов Google Play

Для некоторых продуктов в Firebase Unity SDK для Android требуются Google Play services . Узнайте , какие продукты имеют эту зависимость . Для использования этих продуктов Google Play services должны быть обновлены.

Добавьте следующий оператор using и код инициализации в начало приложения. Вы можете проверить наличие Google Play services и при необходимости обновить их до необходимой версии, прежде чем вызывать любые другие методы в SDK.

using Firebase.Extensions;
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
  var dependencyStatus = task.Result;
  if (dependencyStatus == Firebase.DependencyStatus.Available) {
    // Create and hold a reference to your FirebaseApp,
    // where app is a Firebase.FirebaseApp property of your application class.
       app = Firebase.FirebaseApp.DefaultInstance;

    // Set a flag here to indicate whether Firebase is ready to use by your app.
  } else {
    UnityEngine.Debug.LogError(System.String.Format(
      "Could not resolve all Firebase dependencies: {0}", dependencyStatus));
    // Firebase Unity SDK is not safe to use here.
  }
});

Ваш проект Unity зарегистрирован и настроен для использования Firebase.

Get setup with Apple platforms

Use the following instructions to set up FCM with Unity and Apple platforms.

Upload your APNs authentication key

Upload your APNs authentication key to Firebase. If you don't already have an APNs authentication key, make sure to create one in the Apple Developer Member Center .

  1. Inside your project in the Firebase console, select the gear icon, select Project Settings , and then select the Cloud Messaging tab.

  2. In APNs authentication key under iOS app configuration , click the Upload button to upload your development authentication key, or production authentication key, or both. At least one is required.

  3. Browse to the location where you saved your key, select it, and click Open . Add the key ID for the key (available in the Apple Developer Member Center ) and click Upload .

Enable push notifications on Apple platforms

  1. Click your project in Xcode, then select the General tab from the Editor area .
  2. Scroll to Linked Frameworks and Libraries , then click the + button to add a framework.
  3. In the window that appears, scroll to UserNotifications.framework , click that entry, then click Add .
  4. Click your project in Xcode, then select the Capabilities tab from the Editor area .
  5. Switch Push Notifications to On .
  6. Scroll to Background Modes , then switch it to On .
  7. Select the Remote notifications checkbox under Background Modes .

Initialize Firebase Cloud Messaging

The Firebase Cloud Message library will be initialized when adding handlers for either the TokenReceived or MessageReceived events.

Upon initialization, a registration token is requested for the client app instance. The app will receive the token with the OnTokenReceived event, which should be cached for later use. You'll need this token if you want to target this specific device for messages.

In addition, you will need to register for the OnMessageReceived event if you want to be able to receive incoming messages.

The setup will look like this:

public void Start() {
  Firebase.Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived;
  Firebase.Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived;
}

public void OnTokenReceived(object sender, Firebase.Messaging.TokenReceivedEventArgs token) {
  UnityEngine.Debug.Log("Received Registration Token: " + token.Token);
}

public void OnMessageReceived(object sender, Firebase.Messaging.MessageReceivedEventArgs e) {
  UnityEngine.Debug.Log("Received a new message from: " + e.Message.From);
}

Get setup with Android platforms

Use the following instructions to setup FCM with Unity and Android platforms.

Configure an Android entry point Activity

Firebase Cloud Messaging comes bundled with a custom entry point activity that replaces the default UnityPlayerActivity . If you are not using a custom entry point, this replacement happens automatically and you shouldn't have to take any additional action.

The Firebase Cloud Messaging Unity Plugin on Android comes bundled with two additional files:

  • Assets/Plugins/Android/libmessaging_unity_player_activity.jar contains an activity called MessagingUnityPlayerActivity that replaces the standard UnityPlayerActivity .
  • Assets/Plugins/Android/AndroidManifest.xml instructs the app to use MessagingUnityPlayerActivity as the entry point to the app.

These files are provided because the default UnityPlayerActivity does not handle onStop , onRestart activity lifecycle transitions or implement the onNewIntent which is necessary for Firebase Cloud Messaging to correctly handle incoming messages.

Configure a custom entry point Activity

If your app does not use the default UnityPlayerActivity you will need to remove the supplied AndroidManifest.xml and make sure that your custom activity properly handles all transitions of the Android Activity Lifecycle (an example of how to do this is shown below). If your custom activity extends UnityPlayerActivity you can instead extend com.google.firebase.MessagingUnityPlayerActivity which implements all necessary methods.

If you are using a custom Activity and not extending com.google.firebase.MessagingUnityPlayerActivity , you should include the following snippets in your Activity.

/**
 * Workaround for when a message is sent containing both a Data and Notification payload.
 *
 * When the app is in the background, if a message with both a data and notification payload is
 * received the data payload is stored on the Intent passed to onNewIntent. By default, that
 * intent does not get set as the Intent that started the app, so when the app comes back online
 * it doesn't see a new FCM message to respond to. As a workaround, we override onNewIntent so
 * that it sends the intent to the MessageForwardingService which forwards the message to the
 * FirebaseMessagingService which in turn sends the message to the application.
 */
@Override
protected void onNewIntent(Intent intent) {
  Intent message = new Intent(this, MessageForwardingService.class);
  message.setAction(MessageForwardingService.ACTION_REMOTE_INTENT);
  message.putExtras(intent);
  message.setData(intent.getData());
  // For earlier versions of Firebase C++ SDK (< 7.1.0), use `startService`.
  // startService(message);
  MessageForwardingService.enqueueWork(this, message);
}

/**
 * Dispose of the mUnityPlayer when restarting the app.
 *
 * This makes sure that when the app starts up again it does not start with stale data.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
  if (mUnityPlayer != null) {
    mUnityPlayer.quit();
    mUnityPlayer = null;
  }
  super.onCreate(savedInstanceState);
}

New versions of Firebase C++ SDK (7.1.0 onwards) use JobIntentService which requires additional modifications in AndroidManifest.xml file.

<service android:name="com.google.firebase.messaging.MessageForwardingService"
     android:permission="android.permission.BIND_JOB_SERVICE"
     android:exported="false" >
</service>

Message delivery on 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.

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 . This means that FirebaseMessage.Notification will be a null.

В итоге:

App state Уведомление Данные Оба
Передний план Firebase.Messaging.FirebaseMessaging.MessageReceived Firebase.Messaging.FirebaseMessaging.MessageReceived Firebase.Messaging.FirebaseMessaging.MessageReceived
Фон Системный лоток Firebase.Messaging.FirebaseMessaging.MessageReceived Notification: system tray
Data: in extras of the intent.

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. 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>

It is also possible to specify a wildcard to make the intent filter more flexible. For example:

<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>

When users tap a notification containing a link to the scheme and host you specify, your app will start the activity with this intent filter to handle the link.

Prevent auto initialization

FCM generates a registration token for device 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). You can add a metadata value to your Info.plist (not your GoogleService-Info.plist ) on Apple, or your AndroidManifest.xml on 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

To re-enable FCM, you can make a runtime call:

Firebase.Messaging.FirebaseMessaging.TokenRegistrationOnInitEnabled = true;

This value persists across app restarts once set.

Следующие шаги

After you have completed the setup steps, here are a few options for moving forward with FCM for Unity: