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

# Android Studio とプッシュ通知の概要

> Android Studio、Google Play Services、Firebase Cloud Messaging、PlayFab を連携させて、Android クライアント アプリケーションにプッシュ通知を送信します。

## 概要

このチュートリアルは、プッシュ通知を使用した Android と PlayFab の統合をすばやく開始できるように作成されています。

プッシュ通知には、複数のシステムでの構成が必要です。始める前に、インフラストラクチャのしくみについて説明します。このプロセスには、次の 4 つのエンティティが関与します。

1. **Google Play Services**
2. **Firebase Cloud Messaging Service**s (**FCM**、旧 **Google Cloud Messaging** を基盤として構築)
3. **PlayFab Services**
4. **クライアント アプリケーション**

### 1. Google Play Services

Google Play Services は、パッケージ名を使用して Play マーケット上のページを識別します。

例: **com.bob.games.matchthree**

Google Play に登録されると、パッケージ名は一意のアプリケーション ID となり、Play ストアからのインストールからなりすましの防止まで、さまざまな目的に使用されます。

### 2. Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging サービスは、プッシュ通知を送信、転送、配信するためのクラウドベースのシステムを提供します。

また、FCM サーバー キーを使用して、他のサービス (PlayFab など) があなたに代わってプッシュ通知を送信することもできます。

### 3. PlayFab Services

PlayFab Services は、FCM サーバー キーを使用してクライアントにプッシュ通知を送信します。

### 4. クライアント サービス

最後に、クライアント アプリケーションが通知を受信し、必要に応じて処理します。

### 4 つの部分への分割

このため、*4 つの異なるシステム*をセットアップする必要があります。そのため、このチュートリアルは 4 つの章に分かれており、各部分の構成について説明します。

> [!NOTE]
>
> システムを構成する*順序*が重要です。

## 前提条件

* Google アカウントが必要です。
* PlayFab アカウントが必要です。
* Android Asset Studio の [Notification icon generator](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 - プロジェクトの追加](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 - Android アプリへの Firebase の追加](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 SDK と 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 Console の構成

アプリの準備ができたら、製品の Play ストア ページを管理するために Google Console プロジェクトを作成することになるでしょう。GooglePlay プロジェクトを作成し、それを Firebase プロジェクトにリンクするプロセスを見ていきましょう。

まず、[Google Play Console ページ](https://play.google.com/apps/publish)にアクセスし、次の図に示すように新しいプロジェクトを作成します。

![Google Play - Console ページ](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 Console プロジェクト**ページが開きます。

* サイド メニューで **\[サービスと API]** を選択します。

![Google Play Console - サービスと 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 Console** に表示される**送信者 ID** が **Firebase コンソール**の送信者 ID と一致していることを確認してください。

![Google Play Console - 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 Console プロジェクト**が **Firebase プロジェクト**に正常にリンクされました。

### 第 3 章: PlayFab タイトルの構成

この章の目的は、PlayFab Services があなたに代わってプレイヤーにプッシュ通知を送信できるように、PlayFab Services を構成する方法を示すことです。

* まず、タイトルの \[設定] メニューの **\[タイトルの設定]** に移動する必要があります。

* **\[プッシュ通知]** タブを選択します。

* 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 Doc を探します。

* 最新の 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)

* 任意の **Minimum SDK** を選択します。

* 次に、**\[Next]** ボタンを選択します。

![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** テンプレートを使用することをお勧めします。

* 使用するテンプレートを選択します。

* 次に、**\[Next]** ボタンを選択します。

![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)

* 必要に応じてテンプレートを構成します。

* **\[Finish]** ボタンを選択します。

![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 の [Notification icon generator](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 ページに移動し、ダッシュボードを使用して最新の **Push Registration** を探します。

* **プレイヤー 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

- [プッシュ通知の送信](https://docs.xbox.com/ja-jp/services/playfab/api-references/rest/server/account-management/send-push-notification.md)
- [Android 用プッシュ通知](https://docs.xbox.com/ja-jp/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notifications-for-android.md)
- [Android デバイスのプッシュ通知の登録](https://docs.xbox.com/ja-jp/services/playfab/api-references/rest/client/platform-specific-methods/android-device-push-notification-registration.md)
- [プッシュ通知のセットアップ](https://docs.xbox.com/ja-jp/services/playfab/api-references/rest/admin/title-wide-data-management/setup-push-notification.md)
- [テンプレートからのプッシュ通知の送信](https://docs.xbox.com/ja-jp/services/playfab/api-references/rest/server/account-management/send-push-notification-from-template.md)
