Set up a Firebase Cloud Messaging client app with Unity

To write your cross-platform Firebase Cloud Messaging client app with Unity, use the Firebase Cloud Messaging API. The Unity SDK works for both Android and iOS, with some additional setup required for each platform.

Before you begin

Before you can use the Firebase Cloud Messaging, you will need to create a Firebase project, and add the Firebase Unity SDK packages to your Unity project.

Setup:

Prerequisites

Android

iOS

  • Unity 5.0 or later
  • Xcode 8.0 or later
  • A physical iOS device
  • APNs certificate with Push Notifications enabled

If you don't have a Unity project already, you can download one of our quickstart samples and experiment with a specific Firebase feature. If you're using a quickstart, remember to get the bundle identifier from the project settings; you need it for the next step.

Set up your app in the Firebase console

To add Firebase to your app, you need a Firebase project and a Firebase configuration file for your app.

To create a Firebase project:

  1. Go to the Firebase console.

  2. Click Add project, then select or enter a Project name.

    • If you have an existing Google project associated with your app, select the project from the Project name dropdown menu.
    • If you don't have an existing Google project, enter a new Project name.
  3. (Optional) Edit the Project ID.

    Firebase automatically assigns a unique ID to your Firebase project. This identifier displays in publicly visible Firebase services, for example:

    • Default database URL — your-project-id.firebaseio.com
    • Default hosting subdomain — your-project-id.firebaseapp.com
  4. Follow the remaining setup steps, then click Create project (or Add Firebase, if you're using an existing Google project).

Firebase automatically provisions resources for your Firebase project. The process typically takes a few minutes. When the process completes, you'll be taken to the overview page for your Firebase project in the Firebase console.

Android

  1. Click Add Firebase to your Android app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  2. When prompted, enter your app's package name. It's important to enter the package name your app is using; this can only be set when you add an app to your Firebase project.
  3. During the process, you'll download a google-services.json file. You can download this file again at any time.
  4. After you add the initialization code, run your app to send verification to the Firebase console that you've successfully installed Firebase.

iOS

  1. Click Add Firebase to your iOS app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  2. When prompted, enter your app's bundle ID. It's important to enter the bundle ID your app is using; this can only be set when you add an app to your Firebase project.
  3. During the process, you'll download a GoogleService-Info.plist file. You can download this file again at any time.
  4. After you add the initialization code, run your app to send verification to the Firebase console that you've successfully installed Firebase.
  5. Drag the GoogleService-Info.plist downloaded from the Firebase console into any folder in the Unity project.

Add the Firebase Unity SDK to your app

  1. Download the Firebase Unity SDK.
  2. Select the Assets > Import Package > Custom Package menu item.
  3. Import FirebaseMessaging.unitypackage from the directory that matches the version of Unity you use:
    • Unity 5.x and earlier use the .NET 3.x framework, so you need to import the dotnet3/FirebaseMessaging.unitypackage package.
    • Unity 2017.x and newer allow the use of the .NET 4.x framework. If your project is configured to use .NET 4.x, import the dotnet4/FirebaseMessaging.unitypackage package.
  4. When the Import Unity Package window appears, click the Import button.

Initialize the SDK

The Firebase Unity SDK on Android requires Google Play services, which must be up-to-date before the SDK can be used. The following code should be added at the start of your application to check for and optionally update Google Play services to the version required by the Firebase Unity SDK before calling any other methods in the SDK.

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

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

Build your app

Android

  1. Select the File > Build Settings menu option.
  2. Select Android in the Platform list.
  3. Click Switch Platform to select Android as the target platform.
  4. Wait for the spinner (compiling) icon in the bottom right corner of the Unity status bar to stop.
  5. Click Build and Run.

iOS

  1. Select the File > Build Settings menu option.
  2. Select iOS in the Platform list.
  3. Click Switch Platform to select iOS as the target platform.
  4. Wait for the spinner (compiling) icon in the bottom right corner of the Unity status bar to stop.
  5. Click Build and Run.

  6. After Xcode opens, add the UserNotifications.framework.

    1. Click on the project in Xcode and select the General tab from the Editor area.
    2. Scroll down to Linked Frameworks and Libraries and click the + button to add a framework.
    3. In the window that appears, scroll to UserNotifications.framework and click on that entry, then click on Add.
  7. Configure the Xcode project to enable Push Notifications:

    1. Select the project from the Navigator area.
    2. Select the project target from the Editor area.
    3. Select the General tab from the Editor area.
    4. Scroll down to Linked Frameworks and Libraries and click the + button to add a framework.
      • In the window that appears, scroll to UserNotifications.framework and click on that entry, then click on Add. This framework will only appear in Xcode version 8 and higher, required by this library.
    5. Select the Capabilities tab from the Editor area.
    6. Switch Push Notifications to On.
    7. Scroll down to Background Modes and switch it to On.
    8. Tick the Remote notifications box 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 entire setup looks 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);
}

Configuring an Android entry point Activity

On Android, 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 should not have to take any additional action. Apps that do not use the default entry point Activity or that supply their own Assets/Plugins/AndroidManifest.xml will need extra configuration.

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.

Configuring a custom entry point Activity

If your app does not use the default UnityPlayerActivity you will need to remove the supplied AndroidManifest.xml and ensure 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
 * receieved 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());
  startService(message);
}

/**
 * Dispose of the mUnityPlayer when restarting the app.
 *
 * This ensures 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);
}

Note about 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 will not be communicated to FCM. That is, FirebaseMessage.Notification will be a null.

In summary:

App state Notification Data Both
Foreground Firebase.Messaging.FirebaseMessaging.MessageReceived Firebase.Messaging.FirebaseMessaging.MessageReceived Firebase.Messaging.FirebaseMessaging.MessageReceived
Background System tray Firebase.Messaging.FirebaseMessaging.MessageReceived Notification: system tray
Data: in extras of the intent.

Prevent auto initialization

FCM generates an Instance ID, which is used as a registration token within FCM. When an Instance ID is generated the library will upload the identifier and configuration data to Firebase.If you want to get an explicit opt-in before using Instance ID, 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 iOS, 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>

iOS

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.

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

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.

Next steps

After setting up the client app, you are ready to send downstream and topic messages with Firebase. To learn more, see the quickstart sample which demonstrates this functionality.

To add other, more advanced behavior to your app, see the guides for sending messages from an app server:

Keep in mind that you'll need a server implementation to make use of these features.

Оставить отзыв о...

Текущей странице
Нужна помощь? Обратитесь в службу поддержки.