

 AWS Mobile SDK for Xamarin が に含まれるようになりました AWS SDK for .NET。このガイドでは、Mobile SDK for Xamarin のアーカイブバージョンについて説明します。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# SNS を使用してプッシュ通知を受信する (Xamarin Android)
<a name="getting-started-sns-android"></a>

このチュートリアルでは、Amazon Simple Notification Service (SNS) および AWS Mobile SDK for .NET and Xamarin を使用して、Xamarin Android アプリケーションにプッシュ通知を送信する方法について説明します。

## プロジェクトのセットアップ
<a name="project-setup"></a>

### 前提条件
<a name="prerequisites"></a>

このチュートリアルを開始する前に、必ず「[AWS Mobile SDK for .NET and Xamarin をセットアップする](setup.md)」の手順をすべて完了する必要があります。

### SNS のアクセス許可を設定
<a name="set-permissions-for-sns"></a>

[AWS Mobile SDK for .NET and Xamarin をセットアップする](setup.md)のステップ 2 に従って、以下のポリシーをアプリケーションのロールにアタッチします。これにより、SNS にアクセスするための適切な権限がアプリケーションに付与されます。

1. [IAM コンソール](https://console.aws.amazon.com/iam/home)に移動し、設定する IAM ロールを選択します。

1. [**ポリシーのアタッチ**] をクリック後、AmazonSNSFullAccess ポリシーを選択し、[**ポリシーのアタッチ**] をクリックします。

**警告**  
AmazonSNSFullAccess を本番稼働用環境で使用することは推奨されていません。すばやく起動して実行できるように、こちらの環境を使用します。IAM ロールのアクセス許可を指定する方法については、「[IAM ロールのアクセス許可の概要](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies_permissions.html)」を参照してください。

### Google Cloud のプッシュ通知を有効にする
<a name="enable-push-notifications-on-google-cloud"></a>

まず、新しい Google API プロジェクトを追加します。

1. [Google 開発者コンソール](https://console.developers.google.com)に移動します。

1. [**Create Project**] をクリックします。

1. [**New Project**] ボックスにプロジェクト名を入力し、プロジェクト ID をメモしたら (後で使用します)、[**Create**] をクリックします。

次に、プロジェクトの Google クラウド メッセージング (GCM) サービスを有効にします。

1. [Google 開発者コンソール](https://console.developers.google.com)で、新しいプロジェクトが既に選択されています。選択されていない場合は、ページ上部にあるドロップダウンでプロジェクトを選択します。

1. ページ左側のサイドバーから [**APIs & auth (API と Auth)**] を選択します。

1. 検索ボックスに「Android 用 Google クラウドメッセージング」と入力し、**Google Cloud Messaging for Android** リンクをクリックします。

1. [**Enable API (API を有効化)**] をクリックします。

最後に、API キーを取得します。

1. Google 開発者コンソールで、[**APIs & auth (API と Auth)**]>[**Credentials (認証情報)**] の順に選択します。

1. [**Public API access (パブリック API アクセス)**] で、[**Create new key (新しいキーを作成)**] をクリックします。

1. [**Create a new key (新しいキーの作成)**] ダイアログで、[**Server key (サーバーキー)**] をクリックします。

1. 表示されたダイアログボックスで [**Create (作成)**] を選択し、表示された API キーをコピーします。この API キーは、後で認証を実行するために使用します。

### SNS コンソールでプロジェクト ID を使用してプラットフォーム ARN を作成する
<a name="use-project-id-to-create-a-platform-arn-in-sns-console"></a>

1. [SNS コンソール](https://console.aws.amazon.com/sns/v2/home)に移動します。

1. 画面の左側にある [**アプリケーション**] をクリックします。

1. [**プラットフォームアプリケーションの作成**] をクリックして、新しい SNS プラットフォームアプリケーションを作成します。

1. **アプリケーション名**を入力します。

1. [**Push notification platform**] で [**Google Cloud Messaging (GCM)**] を選択します。

1. [**API キー**] と表示されているテキストボックスに API キーを貼り付けます。

1. [**プラットフォームアプリケーションの作成**] をクリックします。

1. 作成したプラットフォームアプリケーションを選択して、アプリケーション ARN をコピーします。

### SNS の NuGet パッケージをプロジェクトに追加する
<a name="add-nuget-package-for-sns-to-your-project"></a>

「[AWS Mobile SDK for .NET and Xamarin をセットアップする](setup.md)」のステップ 4 に従って、Amazon Simple Notification Service の NuGet パッケージをプロジェクトに追加します。

## SNS クライアントを作成する
<a name="create-an-sns-client"></a>

```
var snsClient = new AmazonSimpleNotificationServiceClient(credentials, region);
```

## アプリケーションにリモート通知を登録する
<a name="register-your-application-for-remote-notifications"></a>

Android にリモート通知を登録するには、BroadcastReceiver を作成する必要があります。これにより、Google クラウドメッセージを受信できるようになります。以下のパッケージ名を変更します。ここで、次のように表示されます。

```
[BroadcastReceiver(Permission = "com.google.android.c2dm.permission.SEND")]
[IntentFilter(new string[] {
      "com.google.android.c2dm.intent.RECEIVE"
}, Categories = new string[] {
      "com.amazonaws.sns" /* change to match your package */
})]
[IntentFilter(new string[] {
      "com.google.android.c2dm.intent.REGISTRATION"
}, Categories = new string[] {
      "com.amazonaws.sns" /* change to match your package */
})]
[IntentFilter(new string[] {
      "com.google.android.gcm.intent.RETRY"
}, Categories = new string[] {
      "com.amazonaws.sns" /* change to match your package */
})]
public class GCMBroadcastReceiver: BroadcastReceiver {
      const string TAG = "PushHandlerBroadcastReceiver";
      public override void OnReceive(Context context, Intent intent) {
              GCMIntentService.RunIntentInService(context, intent);
              SetResult(Result.Ok, null, null);
      }
}

[BroadcastReceiver]
[IntentFilter(new[] {
      Android.Content.Intent.ActionBootCompleted
})]
public class GCMBootReceiver: BroadcastReceiver {
      public override void OnReceive(Context context, Intent intent) {
              GCMIntentService.RunIntentInService(context, intent);
              SetResult(Result.Ok, null, null);
      }
}
```

以下は、BroadcastReceiver よりプッシュ通知を受け取り、デバイスの通知バーに通知を表示するサービスです。

```
[Service]
 public class GCMIntentService: IntentService {
  static PowerManager.WakeLock sWakeLock;
  static object LOCK = new object();

  public static void RunIntentInService(Context context, Intent intent) {
    lock(LOCK) {
      if (sWakeLock == null) {
        // This is called from BroadcastReceiver, there is no init.
        var pm = PowerManager.FromContext(context);
        sWakeLock = pm.NewWakeLock(
        WakeLockFlags.Partial, "My WakeLock Tag");
      }
    }

    sWakeLock.Acquire();
    intent.SetClass(context, typeof(GCMIntentService));
    context.StartService(intent);
  }

  protected override void OnHandleIntent(Intent intent) {
    try {
      Context context = this.ApplicationContext;
      string action = intent.Action;

      if (action.Equals("com.google.android.c2dm.intent.REGISTRATION")) {
        HandleRegistration(intent);
      } else if (action.Equals("com.google.android.c2dm.intent.RECEIVE")) {
        HandleMessage(intent);
      }
    } finally {
      lock(LOCK) {
        //Sanity check for null as this is a public method
        if (sWakeLock != null) sWakeLock.Release();
      }
    }
  }

  private void HandleRegistration(Intent intent) {
    string registrationId = intent.GetStringExtra("registration_id");
    string error = intent.GetStringExtra("error");
    string unregistration = intent.GetStringExtra("unregistered");

    if (string.IsNullOrEmpty(error)) {
      var response = await SnsClient.CreatePlatformEndpointAsync(new CreatePlatformEndpointRequest {
        Token = registrationId,
        PlatformApplicationArn = "YourPlatformArn" /* insert your platform application ARN here */
      });
    }
  }

  private void HandleMessage(Intent intent) {
    string message = string.Empty;
    Bundle extras = intent.Extras;
    if (!string.IsNullOrEmpty(extras.GetString("message"))) {
      message = extras.GetString("message");
    } else {
      message = extras.GetString("default");
    }

    Log.Info("Messages", "message received = " + message);
    ShowNotification(this, "SNS Push", message);
    //show the message

  }

  public void ShowNotification(string contentTitle,
  string contentText) {
    // Intent
    Notification.Builder builder = new Notification.Builder(this)
      .SetContentTitle(contentTitle)
      .SetContentText(contentText)
      .SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
      .SetSmallIcon(Resource.Drawable.Icon)
      .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification));

    // Get the notification manager:
    NotificationManager notificationManager = this.GetSystemService(Context.NotificationService) as NotificationManager;

    notificationManager.Notify(1001, builder.Build());
  }
}
```

## SNS コンソールからエンドポイントにメッセージを送信する
<a name="send-a-message-from-the-sns-console-to-your-endpoint"></a>

1. [[SNS コンソール] > [アプリケーション]](https://console.aws.amazon.com/sns/v2/home) の順に移動します。

1. プラットフォームアプリケーションを選択し、エンドポイントを選択したら、[**エンドポイントへの発行**] をクリックします。

1. テキストボックスにテキストメッセージを入力し、[**メッセージの発行**] をクリックしてメッセージを発行します。