[翻訳] Add App Invites to Your App 

[Add App Invites to Your App](https://developers.google.com/app-invites/android/guides/app)を翻訳してみました。
お気づきの点がありましたらコメント頂ければと思います。

以下、関連する投稿へのリンクです。
■ App Invites for Android (Beta)　[公式](https://developers.google.com/app-invites/android/)　[翻訳](http://qiita.com/tnagao3000/items/e443aef14ab2b1d0c1cf) 
■ Try App Invites for Android　[公式](https://developers.google.com/app-invites/android/guides/start)　[翻訳](http://qiita.com/tnagao3000/items/7ae29c615abd2a8cd46a)
■ **Add App Invites to Your App**　[公式](https://developers.google.com/app-invites/android/guides/app)　[翻訳](http://qiita.com/tnagao3000/items/b91435b439186a52a1cc)
■ Integrate App Invites with Google Analytics　[公式](https://developers.google.com/app-invites/android/guides/analytics)　[翻訳](http://qiita.com/tnagao3000/items/0e17f1c99f27f9f973a4)


# Add App Invites to Your App
>
Now that you’ve had the chance to [try the App Invites sample app](https://developers.google.com/app-invites/android/guides/start), this document guides you through adding App Invites to your own app. Before you can do that, you’ll need the following:
>
- [Android Studio and the Android SDK](https://developer.android.com/sdk/index.html)
- [Google Play Services](https://developer.android.com/google/play-services/setup.html)

[App Invitesのサンプルアプリを試す](https://developers.google.com/app-invites/android/guides/start)機会があったので、このドキュメントではあなたのアプリへのApp Invitesの追加をガイドします。　それが出来るようになる前に下記が必要になります。

- [Android Studio and the Android SDK](https://developer.android.com/sdk/index.html)
- [Google Play Services](https://developer.android.com/google/play-services/setup.html)

## Set up your project
>
Update your project's `AndroidManifest.xml` file to include the standard Google Play Services meta data tag:
>
```xml
<meta-data
      android:name="com.google.android.gms.version"
      android:value="@integer/google_play_services_version" />
```
>
The Google Services plugin for [Gradle](https://gradle.org/) parses configuration information from the `google-services.json` file. Add the plugin to your project by updating your top-level `build.gradle` and your app-level `build.gradle` files as follows:
>
1.Add the dependency to your project's top-level `build.gradle`:
>
```
classpath 'com.google.gms:google-services:1.3.0-beta1'
```
>
2.Add the plugin to your app-level `build.gradle`:
>
```
apply plugin: 'com.google.gms.google-services'
```
>
Now, inside your app's build.gradle add a dependency for Google Play Services:
>
```
compile 'com.google.android.gms:play-services:7.5.+'
```

標準のGoogle Play Serviceのmeta dataタグを組み込むため、プロジェクトの`AndroidManifest.xml`ファイルを更新します。

```xml
<meta-data
      android:name="com.google.android.gms.version"
      android:value="@integer/google_play_services_version" />
```
Google Services plugin for [Gradle](https://gradle.org/)は`google-services.json`ファイルの設定情報を解析します。　下記のようにtop-levelの`build.gradle`ファイルとapp-levelの`build.gradle`ファイルを更新してプロジェクトにプラグインを追加します。

1.top-levelの`build.gradle`に依存関係を追加します:

```
classpath 'com.google.gms:google-services:1.3.0-beta1'
```

2.app-levelの`build.gradle`にプラグインを追加します:

```
apply plugin: 'com.google.gms.google-services'
```
そして、あなたのアプリの`build.gradle`にGoogle Play Servicesへの依存関係を追加します:

```
compile 'com.google.android.gms:play-services:7.5.+'
```


## Get a configuration file
>
Click the button below to get a configuration file to add to your project.
>
The configuration file provides service-specific information for your app. To get it, you must select an existing project for your app or create a new one. You'll also need to provide a package name for your app.
>
[Get a Configuration File](https://developers.google.com/mobile/add?platform=android&cntapi=appinvite&cnturl=https:%2F%2Fdevelopers.google.com%2Fapp-invites%2Fandroid%2Fguides%2Fapp%3Fconfigured%3Dtrue%23add%2Dconfig&cntlbl=Continue%20Adding%20App%20Invites)

あなたのプロジェクトに追加する設定ファイルを取得するため、下記のボタンをクリックしてください。

設定ファイルはあなたのアプリにサービス固有情報を提供します。　それを取得するため、あなたのアプリの既存プロジェクトを選択するか、または新しいものを作成する必要があります。　また、あなたはアプリのパッケージ名を提供する必要があります。

[Get a Configuration File](https://developers.google.com/mobile/add?platform=android&cntapi=appinvite&cnturl=https:%2F%2Fdevelopers.google.com%2Fapp-invites%2Fandroid%2Fguides%2Fapp%3Fconfigured%3Dtrue%23add%2Dconfig&cntlbl=Continue%20Adding%20App%20Invites)


## Add the configuration file to your project
>
Copy the `google-services.json` file you just downloaded into the `app/` or `mobile/` directory of your Android Studio project. Open the Android Studio Terminal pane:
>
Mac/Linux
>>
$ mv ***path-to-download***/google-services.json app/
>
Windows
>>
$ move ***path-to-download***/google-services.json app/


Android Studioプロジェクトの`app/`または `mobile/`ディレクトリにダウンロードした`google-services.json`をコピーします。　Android Studioのターミナルを開き下記を実行します：

Mac/Linuxの場合
>
$ mv ***path-to-download***/google-services.json app/

Windowsの場合
>
$ move ***path-to-download***/google-services.json app/


## Sending Invitations
> Start by building an `Intent` using the `AppInviteInvitation.IntentBuilder` class. The intent must include a title. It can also include a message and optional deep link data, as shown below:
>
```java
private void onInviteClicked() {
    Intent intent = new AppInviteInvitation.IntentBuilder(getString(R.string.invitation_title))
            .setMessage(getString(R.string.invitation_message))
            .setDeepLink(Uri.parse(getString(R.string.invitation_deep_link)))
            .build();
    startActivityForResult(intent, REQUEST_INVITE);
}
```   
>
Launching the `AppInviteInvitation` intent opens the contact chooser where the user selects the contacts to invite. Invites are sent via email or SMS. After the user chooses contacts and sends the invite, your app receives a callback to `onActivityResult`:
>
```java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
>
    if (requestCode == REQUEST_INVITE) {
        if (resultCode == RESULT_OK) {
            // Check how many invitations were sent and log a message
            // The ids array contains the unique invitation ids for each invitation sent
            // (one for each contact select by the user). You can use these for analytics
            // as the ID will be consistent on the sending and receiving devices.
            String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
            Log.d(TAG, getString(R.string.sent_invitations_fmt, ids.length));
        } else {
            // Sending failed or it was canceled, show failure message to the user
            showMessage(getString(R.string.send_failed));
        }
    }
}
``` 

`AppInviteInvitation.IntentBuilder`クラスを使用して`Intent`を作ることから始めます。　Intentにはタイトルが必須です。　それはまた以下のようにメッセージとオプションのディープリンクを含むことも出来ます。

```java
private void onInviteClicked() {
    Intent intent = new AppInviteInvitation.IntentBuilder(getString(R.string.invitation_title))
            .setMessage(getString(R.string.invitation_message))
            .setDeepLink(Uri.parse(getString(R.string.invitation_deep_link)))
            .build();
    startActivityForResult(intent, REQUEST_INVITE);
}
```   
`AppInviteInvitation` intentを発行すると、ユーザーが招待する連絡先を選択するための連絡先選択画面が開きます。　招待状はメールまたはSMSで送られます。　ユーザーが連絡先を選択して送信した後、あなたのアプリは`onActivityResult`でコールバックを受け取ります：

```java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);

    if (requestCode == REQUEST_INVITE) {
        if (resultCode == RESULT_OK) {
            // Check how many invitations were sent and log a message
            // The ids array contains the unique invitation ids for each invitation sent
            // (one for each contact select by the user). You can use these for analytics
            // as the ID will be consistent on the sending and receiving devices.
            String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
            Log.d(TAG, getString(R.string.sent_invitations_fmt, ids.length));
        } else {
            // Sending failed or it was canceled, show failure message to the user
            showMessage(getString(R.string.send_failed));
        }
    }
}
``` 

## Receiving Invitations
>
When a user receives and clicks an invitation, the invitation flow branches depending upon whether or not your app is already installed on the device.

ユーザーが招待状を受け取ってクリックしたとき、招待フローはデバイスにあなたのアプリが既にインストールされているかどうかによって分岐します。

### App is already installed
> If the user has already installed your app, the app will receive an Intent containing the optional deep link data. Implement the following code to respond to the invitation:
>
```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
>
    if (savedInstanceState == null) {
        // No savedInstanceState, so it is the first launch of this activity
        Intent intent = getIntent();
        if (AppInviteReferral.hasReferral(intent)) {
            // In this case the referral data is in the intent launching the MainActivity,
            // which means this user already had the app installed. We do not have to
            // register the Broadcast Receiver to listen for Play Store Install information
            launchDeepLinkActivity(intent);
        }
    }
}
```    

ユーザーが既にあなたのアプリをインストールしている場合、アプリはオプションのディープリンクを含むIntentを受け取ります。　招待状に応じるには下記コードを実装します。

```java
@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...

    if (savedInstanceState == null) {
        // No savedInstanceState, so it is the first launch of this activity
        Intent intent = getIntent();
        if (AppInviteReferral.hasReferral(intent)) {
            // In this case the referral data is in the intent launching the MainActivity,
            // which means this user already had the app installed. We do not have to
            // register the Broadcast Receiver to listen for Play Store Install information
            launchDeepLinkActivity(intent);
        }
    }
}
```    


### App is not installed
> If the user has not yet installed the app, the user can choose to install the app from the Google Play Store, and the first time your app is opened the Google Play Store broadcasts an Intent with the action `“com.android.vending.INSTALL_REFERRER`. Register a broadcast receiver in your app’s `AndroidManifest.xml` to intercept this broadcast:
>
```xml
<receiver
    android:name="com.google.android.gms.samples.appinvite.ReferrerReceiver"
    android:exported="true"
    tools:ignore="ExportedReceiver">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>
```    
>
The `ReferrerReceiver` class looks like this:
>
```java
public class ReferrerReceiver extends BroadcastReceiver {
>
    public ReferrerReceiver() {}
>
    @Override
    public void onReceive(Context context, Intent intent) {
        // Create deep link intent with correct action and add play store referral information
        Intent deepLinkIntent = AppInviteReferral.addPlayStoreReferrerToIntent(intent,
                new Intent(context.getString(R.string.action_deep_link)));
>
        // Let any listeners know about the change
        LocalBroadcastManager.getInstance(context).sendBroadcast(deepLinkIntent);
    }
}
```    
>
The Google Play Store broadcast contains all of the information your app needs from the invitation. One way to handle it is to let the `ReferrerReceiver` take the global broadcast from the Play Store, then re-broadcast a new intent with the deep link data. `MainActivity` listens for this broadcast by registering a receiver in the `onStart` method, then unregistering in `onStop`. When your Activity receives this local re-broadcast, it can then launch the appropriate activity based on the deep Link content:

>
```java
private void registerDeepLinkReceiver() {
    // Create local Broadcast receiver that starts DeepLinkActivity when a deep link
    // is found
    mDeepLinkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (AppInviteReferral.hasReferral(intent)) {
                launchDeepLinkActivity(intent);
            }
        }
    };
>
    IntentFilter intentFilter = new IntentFilter(getString(R.string.action_deep_link));
    LocalBroadcastManager.getInstance(this).registerReceiver(
            mDeepLinkReceiver, intentFilter);
}
>
private void unregisterDeepLinkReceiver() {
    if (mDeepLinkReceiver != null) {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mDeepLinkReceiver);
    }
}
>
/**
 * Launch DeepLinkActivity with an intent containing App Invite information
 */
private void launchDeepLinkActivity(Intent intent) {
    Log.d(TAG, "launchDeepLinkActivity:" + intent);
    Intent newIntent = new Intent(intent).setClass(this, DeepLinkActivity.class);
    startActivity(newIntent);
}
```    

ユーザーがまだアプリをインストールしていない場合、ユーザーはGoogle Playストアからアプリをインストールすることを選択できます。　そしてアプリの初回起動時にGoogle Playストアは`"com.android.vending.INSTALL_REFERRER"` actionを含むIntentをブロードキャストします。　このブロードキャストを受信するため、あなたのアプリの`AndroidManifest.xml`にブロードキャストレシーバーを登録してください。

```xml
<receiver
    android:name="com.google.android.gms.samples.appinvite.ReferrerReceiver"
    android:exported="true"
    tools:ignore="ExportedReceiver">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>
```    
`ReferrerReceiver`クラスは次のようになります。

```java
public class ReferrerReceiver extends BroadcastReceiver {

    public ReferrerReceiver() {}

    @Override
    public void onReceive(Context context, Intent intent) {
        // Create deep link intent with correct action and add play store referral information
        Intent deepLinkIntent = AppInviteReferral.addPlayStoreReferrerToIntent(intent,
                new Intent(context.getString(R.string.action_deep_link)));

        // Let any listeners know about the change
        LocalBroadcastManager.getInstance(context).sendBroadcast(deepLinkIntent);
    }
}
```    

Google Playストアのブロードキャストは、あなたのアプリが必要とする招待状からの全ての情報を含みます。　それを処理する１つの方法は、`ReferrerReceiver`にPlayストアからのグローバルブロードキャストを受信させ、そしてディープリンクを含む新しいIntentを再度ブロードキャストすることです。　`MainActivity`はレシーバーを`onStart`メソッドで登録し、`onStop`メソッドで解除することでこのブロードキャストを受信します。　あなたのActivityがこのローカルな再ブロードキャストを受信したとき、そのActivityはディープリンクの中身に基づいて適切なActivityを起動することが出来ます。

```java
private void registerDeepLinkReceiver() {
    // Create local Broadcast receiver that starts DeepLinkActivity when a deep link
    // is found
    mDeepLinkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (AppInviteReferral.hasReferral(intent)) {
                launchDeepLinkActivity(intent);
            }
        }
    };

    IntentFilter intentFilter = new IntentFilter(getString(R.string.action_deep_link));
    LocalBroadcastManager.getInstance(this).registerReceiver(
            mDeepLinkReceiver, intentFilter);
}

private void unregisterDeepLinkReceiver() {
    if (mDeepLinkReceiver != null) {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mDeepLinkReceiver);
    }
}

/**
 * Launch DeepLinkActivity with an intent containing App Invite information
 */
private void launchDeepLinkActivity(Intent intent) {
    Log.d(TAG, "launchDeepLinkActivity:" + intent);
    Intent newIntent = new Intent(intent).setClass(this, DeepLinkActivity.class);
    startActivity(newIntent);
}
```    

## Tracking Invitations
> After your app has received an invitation and taken the intended actions, it should call the `updateInvitationOnAppInstalled` method to mark the invitation as successful:
>
```java
private void updateInvitationStatus(Intent intent) {
    String invitationId = AppInviteReferral.getInvitationId(intent);
>
    // Note: these  calls return PendingResult(s), so one could also wait to see
    // if this succeeds instead of using fire-and-forget, as is shown here
    if (AppInviteReferral.isOpenedFromPlayStore(intent)) {
        AppInvite.AppInviteApi.updateInvitationOnInstall(mGoogleApiClient, invitationId);
    }
>
    // If your invitation contains deep link information such as a coupon code, you may
    // want to wait to call `convertInvitation` until the time when the user actually
    // uses the deep link data, rather than immediately upon receipt
    AppInvite.AppInviteApi.convertInvitation(mGoogleApiClient, invitationId);
}
```    
>
The code above requires a connected [GoogleApiClient](https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.html) with `AppInvite.API` enabled.

あなたのアプリが招待状を受け取って意図したアクションを行った後、招待に成功とマークするため、`updateInvitationOnAppInstalled`メソッドを呼ぶべきです。

```java
private void updateInvitationStatus(Intent intent) {
    String invitationId = AppInviteReferral.getInvitationId(intent);

    // Note: these  calls return PendingResult(s), so one could also wait to see
    // if this succeeds instead of using fire-and-forget, as is shown here
    if (AppInviteReferral.isOpenedFromPlayStore(intent)) {
        AppInvite.AppInviteApi.updateInvitationOnInstall(mGoogleApiClient, invitationId);
    }

    // If your invitation contains deep link information such as a coupon code, you may
    // want to wait to call `convertInvitation` until the time when the user actually
    // uses the deep link data, rather than immediately upon receipt
    AppInvite.AppInviteApi.convertInvitation(mGoogleApiClient, invitationId);
}
```    
上記のコードは`AppInvite.API`が利用可能な接続済みの[GoogleApiClient](https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.html)を必要とします。