> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Android Studio 和推送通知入门

> 将 Android Studio、Google Play 服务、Firebase Cloud Messaging 和 PlayFab 连接起来，向 Android 客户端应用程序发送推送通知。

## 概述

本教程旨在帮助你快速上手集成了推送通知的 Android PlayFab 集成。

推送通知需要在多个系统中进行配置。在开始之前，我们先来了解一下基础结构的工作方式。此过程涉及 4 个实体：

1. **Google Play 服务**
2. **Firebase Cloud Messaging 服务**（**FCM**，构建于旧版 **Google Cloud Messaging** 之上。）
3. **PlayFab 服务**
4. **客户端应用程序**

### 1. Google Play 服务

Google Play 服务使用包名称来识别你在 Play 商店中的页面。

例如：**com.bob.games.matchthree**。

在 Google Play 中注册后，包名称将成为唯一的应用程序 ID，并有多种用途，从通过 Play 商店安装到防止仿冒。

### 2. Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging 服务为你提供基于云的系统，用于发送、定向和传递推送通知。

它还允许其他服务（例如 PlayFab）使用 FCM 服务器密钥代表你发送推送通知。

### 3. PlayFab 服务

PlayFab 服务随后使用 FCM 服务器密钥向你的客户端发送推送通知。

### 4. 客户端服务

最后，你的客户端应用程序可以接收通知并根据需要进行处理。

### 四部分划分

因此，我们需要设置 *4 个不同的系统*。为此，本教程分为 4 章，分别介绍每个部分的配置。

> [!NOTE]
>
> 配置这些系统的*顺序*非常重要。

## 先决条件

* 你必须拥有 Google 帐户。
* 你必须拥有 PlayFab 帐户。
* 使用 Android Asset Studio [通知图标生成器](https://romannurik.github.io/AndroidAssetStudio/icons-notification.html)生成的通知图标。

## 方案

在本教程的这一部分中，我们将构建一个名为 Foo PlayFab App 的应用程序。这是一个具有以下功能的 Android 应用：

* 使用 Android 设备 ID 登录 PlayFab。
* 接收来自 PlayFab 的推送通知。

我们的包名称为 com.foo.playfab.app。

> [!NOTE]
>
> 按照本教程操作时，请务必使用你自己的包名称和游戏名称。

### 第 1 章：配置 Firebase

首先使用 Firebase 的[官方控制台页面](https://console.firebase.google.com/)开始配置 Firebase。你将看到一个可以添加新项目的页面。

* 为此，请选择**添加项目**区域，如下图所示。

![Firebase - 添加项目](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-add-project.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=c6ebf07725bdea073d34718e5d7c3f1d)

* 系统将要求你提供**项目名称**（在本教程中，我们使用 **Foo PlayFab App**，但按照本教程操作时，*请务必*想出你*自己*的名称）。

* 选择**创建项目**按钮以进入下一步。

![Firebase - 创建项目](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-create-project.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=93cc77ef6805ee6472636146800a54e9)

你将被重定向到**新项目仪表板**。

* 通过选择下图所示的区域，向项目中添加新的 **Android 应用程序**。

![Firebase - 将 Firebase 添加到 Android 应用](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-add-to-android-app.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=db71c761512694decfdf3298661322cf)

添加新的**应用程序**需要 3 个步骤。

1. 首先，你必须提供 **Android 包名称**。我们使用的是 **com.foo.playfab.app**，但按照本教程操作时，请务必想出你*自己*的**包名称**。

2. 选择**注册应用**按钮以进入下一步。

![Firebase - 注册 Android 应用](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-register-android-app.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=8949cec22f3514f2833782c065266372)

第 2 步允许你下载名为 **google-services.json** 的设置文件。稍后将在**应用**中使用它来自动配置 **Google** 服务。

* 下载后，选择**继续**按钮以进入下一步。

![Firebase - 添加 Google 设置文件](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-add-google-settings-file.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=003f8a1a55f516e5a3fa60584e283db2)

3. 最后一步提供了有关如何设置生成过程以连接 Firebase 和 Google Play SDK 的信息。

> [!NOTE]
>
> 你可以忽略此信息，因为我们将使用 Android Studio 中内置的自动化工具来自动执行此设置。

* 选择**完成**按钮以继续。

![Firebase - 完成添加到 Android 应用](https://mintcdn.com/microsoft-4404708b/59DtlsYffqki5YJ_/images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-finish-adding-to-android-app.webp?fit=max\&auto=format\&n=59DtlsYffqki5YJ_\&q=85\&s=3ff4fb88ab6c458e6a343ca83afd98f9)

* 添加**应用程序**后，它将显示在仪表板上。

* 此时，配置已完成，我们需要提取 FCM 服务器密钥（我们将使用它来连接 PlayFab 推送通知）。

* 转到**项目设置**，如下图所示。

![Firebase - 项目设置](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-project-settings.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=25453db20ddb38b6c7cd0e6f46578db7)

* 在**项目设置**中，导航到 **Cloud Messaging** 选项卡。

* 找到**服务器密钥**区域（下图中的红色区域）。

* 复制此**密钥**并将其存储在安全且易于访问的位置。

![Firebase - Cloud Messaging - 服务器密钥](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-copy-server-key.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=47549ef555d012d68d2506b12e17d653)

至此，我们已在 Firebase 中完成了启用推送通知所需的所有操作。

### 第 2 章：配置 Google Play 管理中心

当你的应用准备就绪时，你很可能会创建一个 Google 管理中心项目来维护产品的 Play 商店页面。下面我们来完成创建 Google Play 项目并将其链接到 Firebase 项目的过程。

首先访问 [Google Play 管理中心页面](https://play.google.com/apps/publish)，然后创建一个新项目，如下图所示。

![Google Play - 管理中心页面](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-console-page.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=b2764cf59e851638067b05739c9e0bfe)

* 指定**标题**。

> [!NOTE]
>
> 在此示例中，我们使用 **Foo PlayFab App**。按照本教程操作时，请务必想出你*自己*的游戏名称和包名称。

* 选择**创建**按钮以继续。

![Google Play - 创建应用程序](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-create-application.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=ac4858a57d9150e91dbbbe5502004fa1)

* 将打开 **Google Play 管理中心项目**页面。

* 在侧边菜单中选择**服务和 API**。

![Google Play 管理中心 - 服务和 API](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-console-services-and-apis.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=89ed8f41596cf33bcb7d90201e0d799b)

* 将打开**服务配置**页面。
* 找到 **Firebase Cloud Messaging** 面板。
* 选择**链接发送者 ID** 按钮，如下图所示。

![Google Play - FCM 面板 - 链接发送者 ID](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-fcm-link-sender-id.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=c38ceb863412115eadb603d7b045e2c4)

要链接**发送者 ID**：

* 使用你在上一章中使用 Firebase 控制台时获得（并保存）的 FCM 服务器密钥。
* 完成后，选择**链接**按钮，如我们的示例所示。

![Google Play - 链接发送者 ID - 添加 FCM API 密钥](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-add-fcm-api-key.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=09e18dd1c6e80d94ffbbea649b7943ca)

* 花点时间验证 **Google Play 管理中心**中显示的**发送者 ID** 是否与 **Firebase 控制台**中的发送者 ID 匹配，如下例所示。

![Google Play 管理中心 - Firebase 控制台 - 匹配发送者 ID](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-firebase-match-sender-id.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=4ddb06d507e22df96db776b3e74fd3c6)

至此，**Google Play 管理中心项目**已成功链接到 **Firebase 项目**。

### 第 3 章：配置 PlayFab 游戏

本章的目的是向你展示如何配置 PlayFab 服务，以便其能够代表你向玩家发送推送通知。

* 首先，你必须转到游戏“设置”菜单中的**游戏设置**。

* 选择**推送通知**选项卡。

* 对于 Android 选项，选择**设置**图标。

![PlayFab - 推送通知 - Android 设置](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-push-notifications-android-settings.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=4eec7a15301af9539810665d379e4dd2)

* 系统将要求你提供 **Google 服务器 API 密钥**。

* 复制你通过 Firebase 控制台获得的密钥，如下面提供的示例所示。

![PlayFab - Firebase 控制台 - 添加服务器 API 密钥](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-firebase-add-server-api-key.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=37afb2d4a347067d24e0025d5db1c622)

* 如果一切正确，你将看到一个页面，显示**推送通知**为**活动**状态。

![PlayFab - 推送通知 - 活动](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-push-notifications-android-active.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=968a305d91cfbd117a34cab960fd28d1)

PlayFab 游戏的配置到此结束。

### 第 4 章：配置 Android Studio 项目

要使用 PlayFab JavaSDK，你需要 PlayFab Client JavaSDK 及其依赖项 Google GSON。

* 在此处下载 PlayFab 客户端 JavaSDK JAR 库。

* 查找 `client-sdk-*.jar`，如果需要，还可以查找相应的 Java 文档。

* 下载最新的 Google GSON。

* 查找 `gson-*.jar`。

* 将前面提到的 .jar 文件放在手边。

首先创建一个常规的 Android Studio 项目。

* 验证**包名称**是否与你在本教程中（例如在 Firebase 中）使用的包名称匹配。

> [!NOTE]
>
> 在*本*示例中，我们使用的是 **com.foo.playfab.app**，但按照本教程操作时，请记得想出你自己的包名称和游戏名称。

![Android Studio - 新建项目 - 添加应用名称](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-new-project-add-app-name.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=e3a6f68571ac08857f7e1784409e18a4)

* 根据你的选择选择**最低 SDK**。

* 然后选择**下一步**按钮。

![Android Studio - 新建项目 - 选择最低 SDK](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-new-project-select-min-sdk.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=37acc7e58f141a91bbc54b598e764640)

对于本教程，我们建议从 **Empty Activity** 模板开始。

* 选择要使用的模板。

* 然后选择**下一步**按钮。

![Android Studio - 新建项目 - 选择模板](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-new-project-select-template.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=26ee148418e7ea9ffb651dcef5b5dc72)

* 根据需要配置模板。

* 选择**完成**按钮。

![Android Studio - 新建项目 - 完成](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-new-project-finish.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=f79cb46f260919d023e11c75d6ec9189)

打开新创建的项目后：

* 切换到 **Project** 选项卡 **(1)**。

> [!NOTE]
>
> 在上一章中，你从 Firebase 控制台下载了 `google-services.json` 配置文件。在下一步中使用此文件。

* 验证此文件是否位于 **App** 文件夹下 **(2)**。
* 然后，导航到 **Tools (3)**。
* 选择 **Firebase (4)**，如下面提供的示例所示。

![Android Studio - 将配置文件添加到项目](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-add-config-file.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=71251ee117e53ba0ea52d14dd5ab94b6)

**Firebase Assistant** 将在窗口右侧打开。

* 找到 **Cloud Messaging** 文件夹，然后选择 **Set up Firebase Cloud Messaging**，如下所示。

![Android Studio - Firebase Assistant - 设置 Cloud Messaging](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-firebase-set-up-cloud-messaging.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=c1ab23fad1d9ce59d043f8a817ff2634)

* 在 **Firebase Notifications Assistant** 中，选择 **Add FCM to your app (1)** 按钮，如下图所示。
* 将打开一个对话框，指示将通过 **Gradle** 添加新的依赖项。
* 选择 **Accept Changes (2)** 以批准更改。

> [!NOTE]
>
> 遗憾的是，**Gradle** 同步过程 (**3**) 自动添加的依赖项不正确，并会报告失败！

* 要正确设置依赖项，请将自动添加的语句替换为以下内容：

  `implementation 'com.google.firebase:firebase-core:16.0.3`\
  `implementation 'com.google.firebase:firebase-messaging:17.0.0`

![Android Studio - Firebase Assistant - 将 FCM 添加到你的应用](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-firebase-add-fcm-to-your-app.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=6e068982118ca54c1c54aa211854059a)

该过程完成后：

* 验证 **Firebase Notifications Assistant** 是否指示依赖项现已正确设置 **(1)**。

> [!NOTE]
>
> 在本章开头，我们获取了必要的 JAR 文件。通常，生成文件会自动获取这些文件。

* 要确保这些 JAR 文件列在 **app/libs** 文件夹下 **(2)**，请选择所有文件并右键单击它们。
* 然后选择 **Add as library... (3)**，如下面提供的示例所示。

![Android Studio - Firebase Assistant - 添加为库](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-firebase-add-library.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=cac566cb854d201438a125b093700bf4)

* 使用 Android Asset Studio [通知图标生成器](https://romannurik.github.io/AndroidAssetStudio/icons-notification.html)准备图标，并将其放在 **app/src/main/res** 中。

* 在下面所示的示例中，图标名为 **ic\_stat\_blur\_on**。

![Android Studio - 添加图标](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-add-icons.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=44c75647824acbc7f6eed1764629fb79)

* 最后，选择 **Rebuild Project**。

![Android Studio - 重新生成项目](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-rebuild-project.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=af06d0cc414a65ca537ec1930463b0d4)

现在，我们可以开始实现用于接收和处理通知的代码。我们将修改（并在需要时创建）4 个文件：

1. **app/src/main/AndroidManifest.xml**
2. **app/src/main/java/..packagePath../MainActivity.java**
3. **app/src/main/java/..packagePath../FooAppFirebaseInstanceIdService.java**
4. **app/src/main/java/..packagePath../FooAppFirebaseMessagingService.java**

> [!NOTE]
>
> 当前实现被设计得尽可能简短，只是为了快速测试通知。有关高质量的最佳做法和更复杂的实现示例，请参阅 [FCM 指南](https://firebase.google.com/docs/cloud-messaging/concept-options)。

#### AndroidManifest.xml

在以下代码中，将所有 `MY_PACKAGE_IDENTIFIER` 占位符替换为你*自己*的包标识符。

```xml theme={null}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="MY_PACKAGE_IDENTIFIER">
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- The following block enables our custom Firebase Instance ID Service-->
        <service android:name=".FooAppFirebaseInstanceIdService" android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>

        <service
            android:name=".FooAppFirebaseMessagingService" android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>

    </application>

</manifest>
```

#### MainActivity.java

应根据你的方案替换代码中的以下占位符。

* `PLAYFAB_TITLE_ID`
  * 使用你在 PlayFab Game Manager 中获得的游戏 ID。

* `PACKAGE_IDENTIFIER`
  * 使用与你的设置匹配的 Java 包标识符。

```java theme={null}
package PACKAGE_IDENTIFIER;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.playfab.PlayFabClientAPI;
import com.playfab.PlayFabClientModels.*;
import com.playfab.PlayFabErrors;
import com.playfab.PlayFabSettings;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    // Invoked when activity is started
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set PlayFab title
        PlayFabSettings.TitleId = "PLAYFAB_TITLE_ID";

        // Start login operation
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                if(login()) FooAppFirebaseInstanceIdService.setAllowRegisterForPush(true); // Ready to register for push notifications
            }
        });
    }

    public boolean login(){
        LoginWithAndroidDeviceIDRequest request = new LoginWithAndroidDeviceIDRequest();
        request.CreateAccount = true;

        // There are several approaches on getting unique android device id.
        // https://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id
        request.AndroidDeviceId = "qwerty";

        PlayFabErrors.PlayFabResult<LoginResult> response = PlayFabClientAPI.LoginWithAndroidDeviceID(request);
        if(response.Error != null){
            Log.d("Foo PlayFab App",CompileErrorsFromResult(response.Error));
            return false;
        }
        return true;
    }

    // Utility method to compose an error message out of PlayFab result.
    private static String CompileErrorsFromResult(PlayFabErrors.PlayFabError error) {
        if (error == null)
            return null;

        String errorMessage = "";
        if (error.errorMessage != null)
            errorMessage += error.errorMessage;
        if (error.errorDetails != null)
            for (Map.Entry<String, List<String>> pair : error.errorDetails.entrySet())
                for (String msg : pair.getValue())
                    errorMessage += "\n" + pair.getKey() + ": " + msg;
        return errorMessage;
    }
}
```

#### FooAppFirebaseInstanceIdService.java

应根据你的方案替换下面所示代码中的占位符。

* `PACKAGE_IDENTIFIER`
  * 与你的设置匹配的 Java 包标识符。

```java theme={null}
package PACKAGE_IDENTIFIER;

import android.text.TextUtils;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import com.playfab.PlayFabClientAPI;
import com.playfab.PlayFabClientModels;
import com.playfab.PlayFabErrors;
import java.util.List;
import java.util.Map;

public class FooAppFirebaseInstanceIdService extends FirebaseInstanceIdService {

    private static String _token;

    private static boolean _allowRegistration;

    // This is invoked from activity that performs authentication.
    // Once login is complete this method is invoked.
    // If we have a pending token, we use it to register for push notifications
    public static void setAllowRegisterForPush(boolean isAllowed) {
        _allowRegistration = isAllowed;
        if (_allowRegistration && !TextUtils.isEmpty(_token)) {
            registerForPush(_token);
        }
    }

    // Invoked when firebase has fetched a token
    // If we already have logged in, we use new token to register for push
    @Override
    public void onTokenRefresh() {
        _token = FirebaseInstanceId.getInstance().getToken();
        if (_allowRegistration && !TextUtils.isEmpty(_token)) {
            registerForPush(_token);
        }
    }

    private static void registerForPush(String token) {
        PlayFabClientModels.AndroidDevicePushNotificationRegistrationRequest request = new PlayFabClientModels.AndroidDevicePushNotificationRegistrationRequest();
        request.DeviceToken = token;

        PlayFabErrors.PlayFabResult<PlayFabClientModels.AndroidDevicePushNotificationRegistrationResult> response = PlayFabClientAPI.AndroidDevicePushNotificationRegistration(request);

        if (response.Error != null) {
            Log.d("Foo PlayFab App", CompileErrorsFromResult(response.Error));
        }
    }

    // Utility method to compose an error message out of PlayFab result.
    private static String CompileErrorsFromResult(PlayFabErrors.PlayFabError error) {
        if (error == null)
            return null;

        String errorMessage = "";
        if (error.errorMessage != null)
            errorMessage += error.errorMessage;
        if (error.errorDetails != null)
            for (Map.Entry<String, List<String>> pair : error.errorDetails.entrySet())
                for (String msg : pair.getValue())
                    errorMessage += "\n" + pair.getKey() + ": " + msg;
        return errorMessage;
    }

}
```

#### FooAppFirebaseMessagingService.java

应根据你的方案替换下面所示代码中的占位符。

* `PACKAGE_IDENTIFIER`
  * 与你的设置匹配的 Java 包标识符。

```java theme={null}
package com.foo.playfab.app;

import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FooAppFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage message) {
        // Intercept the message here
        Log.d("Foo PlayFab App","Message received: "+message.getNotification().getBody());
    }
}
```

## 测试

此时，你应该能够将应用程序部署到设备。

* 启动应用程序后，它将自动登录并注册推送通知。

* 选择设备上的**主页**按钮以最小化应用程序。*这一点很重要*，因为这样我们才能测试到达系统托盘的通知。

* 接下来，转到 PlayFab 游戏的 Game Manager 页面，并使用仪表板找到最新的**推送注册**。

* 选择**玩家 ID (1)**。

![PlayFab - PlayStream - 事件日志](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-playstream-event-log.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=8f7c5bacba75a46d48ac840dee5bec99)

这将为该玩家打开**发送推送通知**页面。

* 选择**发送推送通知**按钮 **(1)**。

* 输入**标题 (2)**。

* 输入消息正文 **(3)**。

* 通过选择**发送推送通知**按钮 **(4)** 提交更改。

![PlayFab - 发送推送通知](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-send-push-notification.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=e055e70076d9991525fe1668015c0760)

* 验证消息是否到达你的设备。

![Android 应用 - 接收 PlayFab 推送通知](https://mintcdn.com/microsoft-4404708b/3hg2JQs0m7qmDqay/images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-app-receive-playfab-push-notification.png?fit=max\&auto=format\&n=3hg2JQs0m7qmDqay\&q=85\&s=dd679dd51527afebfb287bc2ab59d2c9)

如果消息到达，则说明消息已成功传递到你的应用程序中。

至此，你已成功完成集成。当应用程序实际运行时，你可以使用 **FooAppFirebaseMessagingService** 来处理传入的消息。


## Related topics

- [Android 推送通知](/zh-CN/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notifications-for-android.md)
- [推送通知快速入门](/zh-CN/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/quickstart.md)
- [推送通知](/zh-CN/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/index.md)
- [推送通知模板](/zh-CN/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notification-templates.md)
- [iOS 推送通知](/zh-CN/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notifications-for-ios.md)
