A konzolhoz

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

Step 1: Set up your environment

  • Install Unity 5.3 or later.

  • (iOS only) Ensure that you have access to the following:

    • Xcode 9.4.1 or later
    • CocoaPods 1.4.0 or later
  • Ensure that your Unity project targets the appropriate OS level:

    • For iOS — target iOS 8 or later
    • For Android — target API level 16 (Jelly Bean) or later
  • Set up a device or emulator for running your Unity project.

    • For iOS — For Firebase Cloud Messaging, you'll need:

      • A physical iOS device
      • APNs certificate with Push Notifications enabled
    • For AndroidEmulators must use an emulator image with Google Play.

  • Sign into Firebase using your Google account.

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

Step 2: 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 3: Register your Unity project with Firebase

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

  1. In the center of the Firebase console's 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.

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

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

    1. Open your Unity project in your Unity IDE.

    2. Navigate to Build Settings > iOS or Android > Player Settings > Other Settings.

      The Unity project's ID is the Bundle Identifier value. (example ID: com.yourcompany.unity-project-name)

    3. Enter each platform-specific ID in the appropriate field:

      • 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.
  4. (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.

  5. Click Register app.

Step 4: Add Firebase configuration files to your Unity project

  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.

    • Before moving your config file, make sure the config file is not appended with additional characters, like (2).
    • You can place the Firebase config files anywhere within the Assets folder.
  3. Back in the Firebase console, in the setup workflow, click Next.

Step 5: Add a Firebase SDK to your Unity project

  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 to import the Firebase Cloud Messaging SDK (FirebaseMessaging.unitypackage).

    You can import any other supported Firebase product, as well.

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

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

Step 6: 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 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.

Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(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.

Step 7: 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 8: 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
 * 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.