

이제 Xamarin용 AWS Mobile SDK가에 포함됩니다 AWS SDK for .NET. 이 안내서에서는 Xamarin용 모바일 SDK의 아카이브된 버전을 참조합니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 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. 페이지 왼쪽의 사이드바에서 **API 및 인증**을 선택합니다.

1. 검색 상자에서 "Google Cloud Messaging for Android"를 입력하고 **Google Cloud Messaging for Android** 링크를 클릭합니다.

1. **API 활성화**를 클릭합니다.

마지막으로 API 키를 받습니다.

1. Google 개발자 콘솔에서 **APIs & auth(API 및 인증)** > **Credentials(자격 증명)**을 선택합니다.

1. **퍼블릭 API 액세스** 아래에서 **새 키 생성**을 클릭합니다.

1. **새 키 생성** 대화 상자에서 **서버 키**를 클릭합니다.

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. **푸시 알림 플랫폼**으로 **Google 클라우드 메시징(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. 텍스트 상자에 텍스트 메시지를 입력하고 **메시지 게시**를 클릭하여 메시지를 게시합니다.