

適用於 Xamarin 的 AWS Mobile SDK 現在已包含在 中 適用於 .NET 的 AWS SDK。本指南參考 Mobile SDK for Xamarin 的封存版本。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 SNS (Xamarin Android) 接收推播通知
<a name="getting-started-sns-android"></a>

本教學課程說明如何使用 Amazon Simple Notification Service (SNS) 和適用於 .NET 和 Xamarin 的 AWS Mobile SDK，將推送通知傳送至 Xamarin Android 應用程式。

## 專案設定
<a name="project-setup"></a>

### 先決條件
<a name="prerequisites"></a>

開始本教學課程之前，您必須完成[設定適用於 .NET 和 Xamarin 的 AWS Mobile SDK](setup.md) 上的所有說明。

### 設定 SNS 的許可
<a name="set-permissions-for-sns"></a>

請遵循[設定適用於 .NET 和 Xamarin 的 AWS Mobile SDK](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. 按一下**建立專案**。

1. 在**新增專案**方塊中，輸入專案名稱，記下專案 ID （稍後需要），然後按一下**建立**。

接著，為您的專案啟用 Google Cloud Messaging (GCM) 服務：

1. 在 [Google 開發人員主控台](https://console.developers.google.com)中，應該已選取您的新專案。如果沒有，請在頁面頂端的下拉式清單中選取它。

1. 從頁面左側的側邊列中選取 **APIs & 驗證**。

1. 在搜尋方塊中，輸入「Google Cloud Messaging for Android」，然後按一下 **Google Cloud Messaging for Android** 連結。

1. 按一下**啟用 API**。

最後，取得 API 金鑰：

1. 在 Google 開發人員主控台中，選取 **APIs & 驗證 > ****登入**資料。

1. 在**公有 API 存取**下，按一下**建立新金鑰**。

1. 在**建立新的金鑰**對話方塊中，按一下**伺服器金鑰**。

1. 在產生的對話方塊中，按一下**建立**並複製顯示的 API 金鑰。您將使用此 API 金鑰稍後執行身分驗證。

### 使用專案 ID 在 SNS 主控台中建立平台 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. 針對**推播通知平台**選取 **Google Cloud Messaging (GCM)**。

1. 將 API 金鑰貼到標記為 **API 金鑰**的文字方塊中。

1. 按一下**建立平台應用程式**。

1. 選取您剛建立的平台應用程式，並複製應用程式 ARN。

### 將 SNS 的 NuGet 套件新增至您的專案
<a name="add-nuget-package-for-sns-to-your-project"></a>

請遵循[設定適用於 .NET 和 Xamarin 的 AWS Mobile SDK](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 上註冊遠端通知，您需要建立可接收 Google Cloud 訊息的 BroadcastReceiver。在出現提示的情況下變更以下套件名稱：

```
[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. 在文字方塊中輸入文字訊息，然後按一下**發佈訊息**以發佈訊息。