Set up a Firebase Cloud Messaging client app with Unity (original) (raw)
To write your cross-platform Firebase Cloud Messaging client app with Unity, use theFirebase 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 yourApple Developer account.
* Enable Push Notifications in XCode under App > Capabilities. - For Android —Emulators must use an emulator image with Google Play.
- For iOS or tvOS — Set up a physical device to run your app, and complete these tasks:
- Sign into Firebase using your Google account.
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.
Create a Firebase project
- In the Firebase console, click Add project.
- To add Firebase resources to an existing Google Cloud project, enter its project name or select it from the dropdown menu.
- To create a new project, enter the desired project name. You can also optionally edit the project ID displayed below the project name.
- If prompted, review and accept the Firebase terms.
- Click Continue.
- (Optional) Set up Google Analytics for your project, which enables you to have an optimal experience using any of the following Firebase products:
Firebase Crashlytics Firebase Cloud Messaging Firebase In-App Messaging Firebase Remote Config Remote Config personalization Firebase A/B Testing Either select an existingGoogle Analytics account or to create a new account. If you create a new account, select yourAnalytics reporting location, then accept the data sharing settings and Google Analytics terms for your project. - Click Create project (or Add Firebase, if you're using an existing Google Cloud project).
Firebase automatically provisions resources for your Firebase project. When the process completes, you'll be taken to the overview page for your Firebase project in the Firebase console.
Step 2: Register your app with Firebase
You can register one or more apps or games to connect with your Firebase project.
- Go to the Firebase console.
- 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 appto display the platform options. - 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.
- Enter your Unity project’s platform-specific ID(s).
- For iOS — Enter your Unity project’s iOS ID in theiOS bundle ID field.
- For Android — Enter your Unity project’s Android ID in theAndroid package name field.
The terms package name and application ID are often used interchangeably.
Where do you find your Unity project's ID?Open your Unity project in your Unity IDE, then navigate to the settings section for each platform:
- For iOS — Navigate to Build Settings > iOS.
- For Android — Navigate to Android > Player Settings > Other Settings.
Your Unity project's ID is the Bundle Identifier value (example ID:
com.yourcompany.yourproject
).
- (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. - Click Register app.
Step 3: Add Firebase configuration files
- Obtain your platform-specific Firebase configuration file(s) in theFirebase console setup workflow.
- For iOS — Click Download GoogleService-Info.plist.
- For Android — Click Download google-services.json.
What do you need to know about this config file?- The Firebase config file contains unique, but non-secret identifiers for your project. To learn more about this config file, visitUnderstand Firebase Projects.
- You can download your Firebase config fileagain at any time.
- Make sure the config file name is not appended with additional characters, like
(2)
.
- Open the Project window of your Unity project, then move your config file(s) into the
Assets
folder. - Back in the Firebase console, in the setup workflow, click Next.
Step 4: Add Firebase Unity SDKs
- 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.
- In your open Unity project, navigate toAssets > Import Package > Custom Package.
- 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 recommendenabling Google Analyticsin 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 requiresGoogle 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 theApple Developer Member Center.
- Inside your project in the Firebase console, select the gear icon, selectProject Settings, and then select theCloud Messaging tab.
- In APNs authentication key under iOS app configuration, click the Upload button.
- Browse to the location where you saved your key, select it, and clickOpen. Add the key ID for the key (available in the Apple Developer Member Center) and clickUpload.
Enable push notifications on Apple platforms
Step 1: Add user notifications framework
- Click on the project in Xcode, then select the General tab from theEditor area.
- Scroll down to Linked Frameworks and Libraries, then click the **+**button to add a framework.
- In the window that appears, scroll to UserNotifications.framework, click that entry, then click Add.
Step 2: Enable push notifications
- Click on the project in Xcode, then select the Capabilities tab from theEditor area.
- Switch Push Notifications to On.
- Scroll down to Background Modes, then switch it to On.
- 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 calledMessagingUnityPlayerActivity
that replaces the standardUnityPlayerActivity
.Assets/Plugins/Android/AndroidManifest.xml
instructs the app to useMessagingUnityPlayerActivity
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 theonNewIntent
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 theAndroid Activity Lifecycle(an example of how to do this is shown below). If your custom activity extends UnityPlayerActivity
you can instead extendcom.google.firebase.MessagingUnityPlayerActivity
which implements all necessary methods.
If you are using a custom Activity and not extendingcom.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.
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 trayData: 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 yourAndroidManifest.xml
on Android:
Android
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.
Handling Messages with Deep Links on 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 do not contain a deep link, this configuration is not necessary. In AndroidManifest.xml:
It is also possible to specify a wildcard to make the intent filter more flexible. For example:
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 thequickstart samplewhich 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 aserver implementation to make use of these features.