> ## 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 Services、Firebase Cloud Messaging、PlayFab を連携させて、Android クライアント アプリケーションにプッシュ通知を送信します。

## 概要

このチュートリアルは、Android の PlayFab 統合とプッシュ通知を稼働させるのに役立つように設計されています。

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

1. **Google Play Services**
2. **Firebase Cloud Messaging Service** (**FCM**、旧 **Google Cloud Messaging** の上に構築)
3. **PlayFab Services**
4. **Client Applications**

### 1. Google Play Services

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

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

Google Play に登録されると、パッケージ名は一意のアプリケーション ID となり、Play Store 経由のインストールから成りすまし防止まで、多くの目的に役立ちます。

### 2. Firebase Cloud Messaging (FCM)

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

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

### 3. PlayFab Services

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

### 4. Client Services

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

### 4 方向の分割

その結果、*4 つの異なるシステム* をセットアップする必要があります。そのため、このチュートリアルは、それぞれの部分の構成を扱う 4 つの章に分割されています。

<Note>
  システムを構成する *順序* は重要です。
</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 とします。

<Info>
  このチュートリアルに従うときは、ご自分のパッケージ名とタイトルを使用してください。
</Info>

### 第 1 章: Firebase の構成

Firebase の構成は、[公式コンソール ページ](https://console.firebase.google.com/) を使用して開始します。新しいプロジェクトを追加できるページが表示されます。

* これを行うには、次の画像に示すように **Add project** エリアを選択します。

<img src="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" alt="Firebase - プロジェクトの追加" width="709" height="601" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-add-project.png" />

* **Project Name** を入力するよう求められます (このチュートリアルでは **Foo PlayFab App** を使用しますが、このチュートリアルに従うときは *独自の* 名前を考えてください)。

* **Create Project** ボタンを選択して次のステップに進みます。

<img src="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" alt="Firebase - プロジェクトの作成" width="662" height="591" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-create-project.png" />

**新しいプロジェクト ダッシュボード** にリダイレクトされます。

* 次の画像に示すエリアを選択して、プロジェクトに新しい **Android Application** を追加します。

<img src="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" alt="Firebase - Android アプリに Firebase を追加" width="801" height="695" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-add-to-android-app.png" />

新しい **Application** を追加するには 3 つの手順が必要です。

1. まず、**Android Package Name** を入力する必要があります。**com.foo.playfab.app** を使用していますが、このチュートリアルに従うときは *独自の* **Package Name** を考えてください。

2. **Register App** ボタンを選択して次のステップに進みます。

<img src="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" alt="Firebase - Android アプリの登録" width="694" height="742" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-register-android-app.png" />

ステップ 2 では、**google-services.json** と呼ばれる設定ファイルをダウンロードできます。これは、後で **App** で **Google** サービスを自動的に構成するために使用されます。

* ダウンロード後、**Continue** ボタンを選択して次のステップに進みます。

<img src="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" alt="Firebase - Google 設定ファイルの追加" width="694" height="742" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-add-google-settings-file.png" />

3. 最終ステップでは、Firebase および Google Play SDK を連携させるためのビルド プロセスの設定方法についての情報が提供されます。

<Note>
  この設定を自動的に実行する Android Studio に組み込まれた自動化ツールを使用するため、この情報は無視してかまいません。
</Note>

* **Finish** ボタンを選択して続行します。

<img src="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" alt="Firebase - Android アプリへの追加を終了" width="689" height="740" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-finish-adding-to-android-app.webp" />

* **Application** が追加されると、ダッシュボードに表示されます。

* この時点で構成は完了しており、FCM サーバー キー (PlayFab プッシュ通知の連携に使用します) を抽出する必要があります。

* 次の画像に示すように **Project settings** に移動します。

<img src="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" alt="Firebase - プロジェクトの設定" width="696" height="547" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-project-settings.png" />

* **Project settings** で **Cloud Messaging** タブに移動します。

* **Server Key** エリア (下の画像の赤いエリア) を見つけます。

* この **Key** をコピーして、安全でアクセスしやすい場所に保存します。

<img src="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" alt="Firebase - Cloud Messaging - サーバー キー" width="855" height="487" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/firebase-copy-server-key.png" />

この時点で、プッシュ通知を有効にするために Firebase で必要なすべてを行いました。

### 第 2 章: Google Play コンソールの構成

アプリの準備ができたら、製品の Play Store ページを維持するために、Google Console プロジェクトを作成する可能性が高いです。GooglePlay プロジェクトを作成し、それを Firebase プロジェクトにリンクするプロセスを見ていきましょう。

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

<img src="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" alt="Google Play - コンソール ページ" width="1097" height="691" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-console-page.png" />

* **Title** を割り当てます。

<Note>
  この例では **Foo PlayFab App** を使用します。このチュートリアルに従う際は、ご自分のタイトルとパッケージ名を考えてください。
</Note>

* **Create** ボタンを選択して続行します。

<img src="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" alt="Google Play - アプリケーションの作成" width="607" height="455" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-create-application.png" />

* **Google Play Console Project** ページが開きます。

* サイド メニューで **Services & APIs** を選択します。

<img src="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" alt="Google Play Console - Services and APIs" width="466" height="604" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-console-services-and-apis.png" />

* **Services configuration** ページが開きます。
* **Firebase Cloud Messaging** パネルを見つけます。
* 次の画像に示すように、**Link a Sender ID** ボタンを選択します。

<img src="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" alt="Google Play - FCM パネル - Sender ID のリンク" width="497" height="650" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-fcm-link-sender-id.png" />

**Sender ID** をリンクするには:

* 前の章で Firebase コンソールを使用しているときに受け取った (そして保存した) FCM サーバー キーを使用します。
* 完了したら、例に示すように **Link** ボタンを選択します。

<img src="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" alt="Google Play - Sender ID のリンク - FCM API キーの追加" width="627" height="360" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-add-fcm-api-key.png" />

* 以下の例に示すように、**Google Play Console** に表示される **Sender ID** が **Firebase Console** のものと一致することを確認する時間を取ります。

<img src="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" alt="Google Play Console - Firebase Console - Sender ID の一致" width="1012" height="480" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/google-play-firebase-match-sender-id.png" />

この時点で、**Google Play Console Project** は **Firebase Project** に正常にリンクされました。

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

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

* まず、タイトルの Settings メニューで **Title settings** に移動する必要があります。

* **Push Notifications** タブを選択します。

* Android オプションで、**Settings** アイコンを選択します。

<img src="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" alt="PlayFab - プッシュ通知 - Android 設定" width="1366" height="835" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-push-notifications-android-settings.png" />

* **Google server API key** を求められます。

* 以下の例に示すように、Firebase コンソールで受け取ったものをコピーします。

<img src="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" alt="PlayFab - Firebase Console - サーバー API キーの追加" width="1131" height="508" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-firebase-add-server-api-key.png" />

* すべてが正しければ、**Push Notifications** が **Active** として表示されるページが表示されます。

<img src="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" alt="PlayFab - プッシュ通知 - アクティブ" width="1366" height="835" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-push-notifications-android-active.png" />

これで、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 プロジェクトを作成します。

* **Package name** がこのチュートリアル全体を通して使用したもの (たとえば Firebase 内) と一致することを確認します。

<Note>
  *この* 例では **com.foo.playfab.app** を使用していますが、このチュートリアルに従うときはご自分のパッケージ名とタイトルを考えてください。
</Note>

<img src="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" alt="Android Studio - 新しいプロジェクト - アプリ名の追加" width="1058" height="734" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-new-project-add-app-name.png" />

* お好みの **Minimum SDK** を選択します。

* 次に **Next** ボタンを選択します。

<img src="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" alt="Android Studio - 新しいプロジェクト - 最小 SDK の選択" width="916" height="740" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-new-project-select-min-sdk.png" />

このチュートリアルでは、まずは **Empty Activity** テンプレートを使用することをお勧めします。

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

* 次に **Next** ボタンを選択します。

<img src="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" alt="Android Studio - 新しいプロジェクト - テンプレートの選択" width="916" height="740" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-new-project-select-template.png" />

* お好みでテンプレートを構成します。

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

<img src="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" alt="Android Studio - 新しいプロジェクト - 終了" width="916" height="740" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-new-project-finish.png" />

新しく作成したプロジェクトを開いたら:

* **Project** タブ **(1)** に切り替えます。

<Note>
  前の章で、Firebase コンソールから `google-services.json` 構成ファイルをダウンロードしました。次のステップでこれを使用します。
</Note>

* このファイルが **App** フォルダー **(2)** の下に配置されていることを確認します。
* 次に、**Tools (3)** に移動します。
* 以下の例に示すように、**Firebase (4)** を選択します。

<img src="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" alt="Android Studio - プロジェクトに構成ファイルを追加" width="873" height="847" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-add-config-file.png" />

**Firebase Assistant** がウィンドウの右側に開きます。

* **Cloud Messaging** フォルダーを見つけ、以下に示すように **Set up Firebase Cloud Messaging** を選択します。

<img src="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" alt="Android Studio - Firebase アシスタント - Cloud Messaging のセットアップ" width="592" height="820" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-firebase-set-up-cloud-messaging.png" />

* **Firebase Notifications Assistant** で、次の画像に示すように **Add FCM to your app (1)** ボタンを選択します。
* **Gradle** を介して新しい依存関係が追加されることを示すダイアログが開きます。
* **Accept Changes (2)** を選択して変更を承認します。

<Note>
  残念ながら、**Gradle** の同期プロセス (**3**) によって自動的に追加される依存関係は正しくなく、失敗が報告されます!
</Note>

* 依存関係を正しく設定するには、自動追加された文を次の内容に置き換えます:

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

<img src="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" alt="Android Studio - Firebase アシスタント - アプリへの FCM の追加" width="1162" height="597" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-firebase-add-fcm-to-your-app.png" />

そのプロセスが完了したら:

* **Firebase Notifications Assistant** が、依存関係が現在正しく設定されていることを示していることを確認します **(1)**。

<Note>
  この章の冒頭で、必要な JAR ファイルを取得しました。通常、ビルド ファイルはこれらのファイルを自動的にフェッチします。
</Note>

* これらの JAR ファイルが **app/libs** フォルダー **(2)** の下にリストされていることを確認するには、すべてのファイルを選択して右クリックします。
* 次に、以下の例に示すように **Add as library... (3)** を選択します。

<img src="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" alt="Android Studio - Firebase アシスタント - ライブラリとして追加" width="1315" height="881" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-firebase-add-library.png" />

* Android Asset Studio の [通知アイコン ジェネレーター](https://romannurik.github.io/AndroidAssetStudio/icons-notification.html) を使用して、アイコンを準備し、**app/src/main/res** の中に配置します。

* 以下の例では、アイコンは **ic\_stat\_blur\_on** と呼ばれます。

<img src="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" alt="Android Studio - アイコンを追加" width="495" height="393" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-add-icons.png" />

* 最後に、**Rebuild Project** を選択します。

<img src="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" alt="Android Studio - プロジェクトの再構築" width="1471" height="849" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-studio-rebuild-project.png" />

これで通知の受信と処理のためのコードを実装し始めることができます。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 Guides](https://firebase.google.com/docs/cloud-messaging/concept-options) を検討してください。
</Note>

#### 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());
    }
}
```

## テスト

この時点で、アプリケーションをデバイスにデプロイできるはずです。

* アプリケーションを起動すると、自動的にログインしてプッシュ通知に登録します。

* デバイスの **Home** ボタンを選択して、アプリケーションを最小化します。*これは重要です*。システム トレイに届く通知をテストできるようにするためです。

* 次に、PlayFab タイトルの Game Manager ページに移動し、ダッシュボードを使用して最新の **Push Registration** を見つけます。

* **Player ID (1)** を選択します。

<img src="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" alt="PlayFab - PlayStream - イベント ログ" width="524" height="330" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-playstream-event-log.png" />

これにより、そのプレイヤーの **Send Push Notification** ページが開きます。

* **Send Push Notification** ボタン **(1)** を選択します。

* **Title (2)** を入力します。

* メッセージの本文 **(3)** を入力します。

* **Send Push Notification** ボタン **(4)** を選択して変更をコミットします。

<img src="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" alt="PlayFab - プッシュ通知の送信" width="1308" height="560" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/playfab-send-push-notification.png" />

* メッセージがデバイスに届くことを確認します。

<img src="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" alt="Android アプリ - PlayFab プッシュ通知の受信" width="378" height="672" data-path="images/playfab/live-service-management/game-configuration/title-communications/tutorials/android-app-receive-playfab-push-notification.png" />

メッセージが届けば、メッセージがアプリケーションに正常に配信されています。

この時点で、統合が正常に完了しました。**FooAppFirebaseMessagingService** を使用して、アプリケーションが実際に実行されている間に受信メッセージを処理できます。


## Related topics

- [Android 用プッシュ通知](/ja-jp/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notifications-for-android.md)
- [プッシュ通知クイックスタート](/ja-jp/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/quickstart.md)
- [プッシュ通知](/ja-jp/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/index.md)
- [プッシュ通知テンプレート](/ja-jp/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notification-templates.md)
- [iOS 用プッシュ通知](/ja-jp/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/push-notifications-for-ios.md)
