Documentation

Did you find this helpful?

Push Notifications for Android

Prerequisites

Configure Android Notification Channel

The Google and Firebase developer consoles experience changes regularly. The description below best describes the values you need, and how to get them, as of June 2017:

Google & Firebase Setup:

There are three Google websites you have to use and synchronize. In Google/Firebase, there are both "Projects" and "Apps":

PlayFab requires a server API-Key:

  • You can get this key from Google API Manager, or from the Firebase Console
  • Google API Manager:
    • Select your Project
    • Select Credentials (left menu)
    • The Firebase Project import will have created a ServerKey for you here
  • Firebase Console:
    • Select your Project or App, and find the Settings option (there are many ways to do this, all of which lead you to the same place)
    • In the General tab, this is listed as "Web API Key"
    • In the Cloud Messaging tab, this is listed as "Legacy server key"
  • All of the keys described above should be identical, and they are all the "API Key" described in this document
    • If they are not identical, the "Legacy server key" is the one needed by PlayFab

Using API-Key:

  • Provide your API Key in one of two ways:
    1. Input your key directly into the Game Manager UI: Settings (for your title) > Push Notifications > Android
    2. OR, Call SetupPushNotification using Postman or a Unity project with Server API methods enabled:
      • Name: "your_game_name"
      • Platform: "GCM"
      • Credential: (Google server API key) : “AIza*****ppo”
      • OverwriteOldARN: true
      • You should get an HTTP 200 OK response with similar data

// Postman JSON result output
{
    "code": 200,
    "status": "OK",
    "data": { "ARN" : "arn:*******/GCM/your_game_name" }
}

  • Once set up properly (either method), you should see this in the Game Manager UI Settings (for your title) > Push Notifications > Android

Getting started: Push Notifications for Android + Unity

Set Up Your Unity Project

  • Create a new Unity project
  • [OPTIONAL] Import the PlayFab Unity Editor Extensions package
  • Import the Unity PlayFab SDK package
  • Follow the FCM Unity guide to install FCM messaging, and set up a project for push notifications
    • Once finished, you can continue this guide to receive messages from PlayFab
    • We will give you a complete FCM-ready MonoBehaviour script below, which combines FCM and PlayFab
  • In the FCM guide, you created a monobehavior that set up the Firebase plugin
    • You can continue using that monobehavior, or replace it with ours below

Setting up your first Push Notification

In Unity, open the script you created in the FCM tutorial, and replace the contents with the following:

using PlayFab;
using PlayFab.ClientModels;
using PlayFab.Json;
using UnityEngine;

public class MsgCatcher : MonoBehaviour
{
    public string pushToken;
    public string playFabId;
    public string lastMsg;

    // OnGUI should be deleted/replaced with your own gui - This is only provided for debugging
    public void OnGUI()
    {
        GUI.Label(new Rect(0, 0, Screen.width, 200), pushToken);
        GUI.Label(new Rect(0, 200, Screen.width, Screen.height - 200), lastMsg);
    }

    private void OnPfFail(PlayFabError error)
    {
        Debug.Log("PlayFab: api error: " + error.GenerateErrorReport());
    }

    public void Start()
    {
        // PlayFabSettings.TitleId = "TITLE_ID";
        Firebase.Messaging.FirebaseMessaging.TokenReceived += OnTokenReceived;
        Firebase.Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived;
        LoginToPlayFab();
    }

    private void LoginToPlayFab()
    {
#if UNITY_ANDROID
        var request = new LoginWithAndroidDeviceIDRequest { AndroidDeviceId = SystemInfo.deviceUniqueIdentifier, CreateAccount = true, };
        PlayFabClientAPI.LoginWithAndroidDeviceID(request, OnPfLogin, OnPfFail);
#endif
    }

    private void OnPfLogin(LoginResult result)
    {
        Debug.Log("PlayFab: login successful");
        playFabId = result.PlayFabId;
        RegisterForPush();
    }

    private void RegisterForPush()
    {
        if (string.IsNullOrEmpty(pushToken) || string.IsNullOrEmpty(playFabId))
            return;

#if UNITY_ANDROID
        var request = new AndroidDevicePushNotificationRegistrationRequest {
            DeviceToken = pushToken,
            SendPushNotificationConfirmation = true,
            ConfirmationMessage = "Push notifications registered successfully"
        };
        PlayFabClientAPI.AndroidDevicePushNotificationRegistration(request, OnPfAndroidReg, OnPfFail);
#endif
    }

    private void OnPfAndroidReg(AndroidDevicePushNotificationRegistrationResult result)
    {
        Debug.Log("PlayFab: Push Registration Successful");
    }

    private void OnTokenReceived(object sender, Firebase.Messaging.TokenReceivedEventArgs token)
    {
        Debug.Log("PlayFab: Received Registration Token: " + token.Token);
        pushToken = token.Token;
        RegisterForPush();
    }

    private void OnMessageReceived(object sender, Firebase.Messaging.MessageReceivedEventArgs e)
    {
        Debug.Log("PlayFab: Received a new message from: " + e.Message.From);
        lastMsg = "";
        if (e.Message.Data != null)
        {
            lastMsg += "DATA: " + JsonWrapper.SerializeObject(e.Message.Data) + "\n";
            Debug.Log("PlayFab: Received a message with data:");
            foreach (var pair in e.Message.Data)
                Debug.Log("PlayFab data element: " + pair.Key + "," + pair.Value);
        }
        if (e.Message.Notification != null)
        {
            Debug.Log("PlayFab: Received a notification:");
            lastMsg += "TITLE: " + e.Message.Notification.Title + "\n";
            lastMsg += "BODY: " + e.Message.Notification.Body + "\n";
        }
    }
}

Build and run your Unity project on a device. If you receive a push notification with the text "Push notifications registered successfully", then everything worked as expected.

PLEASE NOTE:

PlayFabSettings.TitleId = "TITLE_ID";

You should set your own TitleId. This example will not work if you don't update this TitleId, because our title is registered with our Firebase keys and settings, not yours. You can do so by un-commenting this line and replacing TITLE_ID with your titleId, or you can choose your title from the optional Editor Extensions plugin mentioned in the previous section

Troubleshooting Android

  • Verify that you can send a test push notification from the Firebase Console
    • If you cannot, then your Firebase plugin is not set up correctly, and you should review the Firebase Documentation to find out why, or contact Firebase Support
  • Ensure your FCM client pushToken is set properly
    • The "OnTokenReceived" function above, should be called and should have a valid token
    • If it is not called, your Firebase plugin is not set up correctly, and you should review the Firebase Documentation to find out why, or contact Firebase Support
  • Ensure your titleId is set to a title you own, and that title has been registered with the server API-Key from your Firebase project

Advanced Features

In server.SendPushNotification, you can use request.Package.CustomData to deliver arbitrary data to the device. In the example above, this is delivered to the section with the comment: Debug.Log("PlayFab: Received a message with data:");

You can customize your client receiver to utilize that data however you like. CustomData is not displayed to the player, so it can be used to deliver game-custom information to your client, or to locally schedule another future notification using the FCM plugin. You can also use request.Package.CustomData or request.AdvancedPlatformDelivery to deliver to many 3rd party plugins. 3rd party plugin delivery is not supported or guaranteed, but is available for advanced users.

Additional Support

For help, example bugs, and related questions, drop us a line over at our support forums.

We are currently only support our services for the standard flow described in this document. If your team is looking for additional functionality with other common push services or plugins, please let us know! We love getting feedback from our developer community.

documentation on the push payload via Amazon SNS:



Did you find this helpful?