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 Apple, with some additional setup required for each platform.

Before you begin

Prerequisites

  • Install Unity 2021 LTS or later. Support for Unity 2020 is considered deprecated, and will no longer be actively supported after the next major release. Earlier versions may also be compatible but won't be actively supported.

  • (Apple platforms only) Install the following:

    • Xcode 13.3.1 or higher
    • CocoaPods 1.12.0 or higher
  • Make sure that your Unity project meets these requirements:

    • For iOS — targets iOS 13 or higher
    • For tvOS - targets tvOS 13 or higher
    • For Android — targets API level 21 (Lollipop) or higher
  • Set up a device or use an emulator to run your Unity project.

    • For iOS or tvOS — Set up a physical device to run your app, and complete these tasks:

      • Obtain an Apple Push Notification Authentication Key for your Apple Developer account.
      • Enable Push Notifications in XCode under App > Capabilities.
    • For AndroidEmulators must use an emulator image with Google Play.

If you don't already have a Unity project and just want to try out a Firebase product, you can download one of our quickstart samples.

Step 1: Create a Firebase project

Before you can add Firebase to your Unity project, you need to create a Firebase project to connect to your Unity project. Visit Understand Firebase Projects to learn more about Firebase projects.

Step 2: Register your app with Firebase

You can register one or more apps or games to connect with your Firebase project.

  1. Go to the Firebase console.

  2. In the center of the project overview page, click the Unity icon () to launch the setup workflow.

    If you've already added an app to your Firebase project, click Add app to display the platform options.

  3. Select which build target of your Unity project that you’d like to register, or you can even select to register both targets now at the same time.

  4. Enter your Unity project’s platform-specific ID(s).

    • For iOS — Enter your Unity project’s iOS ID in the iOS bundle ID field.

    • For Android — Enter your Unity project’s Android ID in the Android package name field.
      The terms package name and application ID are often used interchangeably.

  5. (Optional) Enter your Unity project’s platform-specific nickname(s).
    These nicknames are internal, convenience identifiers and are only visible to you in the Firebase console.

  6. Click Register app.

Step 3: Add Firebase configuration files

  1. Obtain your platform-specific Firebase configuration file(s) in the Firebase console setup workflow.

    • For iOS — Click Download GoogleService-Info.plist.

    • For Android — Click Download google-services.json.

  2. Open the Project window of your Unity project, then move your config file(s) into the Assets folder.

  3. Back in the Firebase console, in the setup workflow, click Next.

Step 4: Add Firebase Unity SDKs

  1. In the Firebase console, click Download Firebase Unity SDK, then unzip the SDK somewhere convenient.

    • You can download the Firebase Unity SDK again at any time.

    • The Firebase Unity SDK is not platform-specific.

  2. In your open Unity project, navigate to Assets > Import Package > Custom Package.

  3. From the unzipped SDK, select the supported Firebase products that you want to use in your app.

    For an optimal experience with Firebase Cloud Messaging, we recommend enabling Google Analytics in your project. Also, as part of setting up Analytics, you need to add the Firebase package for Analytics to your app.

    Analytics enabled

    • Add the Firebase package for Google Analytics: FirebaseAnalytics.unitypackage
    • Add the package for Firebase Cloud Messaging: FirebaseMessaging.unitypackage

    Analytics not enabled

    Add the package for Firebase Cloud Messaging: FirebaseMessaging.unitypackage

  4. In the Import Unity Package window, click Import.

  5. Back in the Firebase console, in the setup workflow, click Next.

Step 5: Confirm Google Play services version requirements

The Firebase Unity SDK for Android requires Google Play services, which must be up-to-date before the SDK can be used.

Add the following using statement and initialization code at the start of your application. You can check for and optionally update Google Play services to the version that is required by the Firebase Unity SDK before calling any other methods in the 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.
  }
});

Your Unity project is registered and configured to use Firebase.

Upload your APNs authentication key for Apple support

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.

  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

Step 1: Add user notifications framework

  1. Click on the project in Xcode, then select the General tab from the Editor area.

  2. Scroll down 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.

Step 2: Enable push notifications

  1. Click on the project in Xcode, then select the Capabilities tab from the Editor area.

  2. Switch Push Notifications to On.

  3. Scroll down to Background Modes, then switch it to On.

  4. 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 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
 * 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 older 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 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);
}

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>

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 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). To do this, add a metadata value to your Info.plist (not your GoogleService-Info.plist) on Apple, 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>

Swift

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.