~~NOCACHE~~ ## SNSからAndroidへプッシュ通知をしてみた。 こんな風に、AndroidDeviceにAmazonSNSからプッシュ通知をしてみたく試してみた。 {{:Aws:SimpleNotificationService:pasted:20230114-225825.png?direct 600x0}} 関連図は下記の感じですが、FirebaseもAndroidStudioも初めて触ったので苦労しました。 {{:Aws:SimpleNotificationService:pasted:20230114-223209.png?direct 600x0}} ### 事前準備 色々手順が長いので分解して・・・以下の事前準備を実施します。 ①[[InfrastructureConstruction:Google:Firebase01|Firebaseへプロジェクトの作成とアプリケーションの登録をします。]] ②[[InfrastructureConstruction:Google:FirebaseCloudMessaging01|CloudMessagingを有効化しサーバーキーを取得します。]] ③[[InfrastructureConstruction:Google:AndroidStudio01|AndroidStudioのプロジェクト作成とFirebaseSDK環境を準備する。]] ### クライアントの実装 [[https://tech-blog.rakus.co.jp/entry/20210326/firebase|こちら]]のサイトが大変参考になりました。(ほぼ流用) {{:Aws:SimpleNotificationService:pasted:20230115-124641.png?direct 400x0}} ①MainActivityの編集(ハイライト行の追加) package mnztech.work.sns import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import com.google.android.gms.tasks.OnCompleteListener import com.google.firebase.messaging.FirebaseMessaging class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { Log.w("MainActivity", "Fetching FCM registration token failed", task.exception) return@OnCompleteListener } // 現行のトークンを取得 val token = task.result // ログに出力 Log.d("MainActivity", "Current token: $token") }) } } ②MyFirebaseMessagingServiseの作成(最終的にこうなりました) %%参考サイトのままだと以下のエラーが出たため、ハイライト行を「PendingIntent.FLAG_MUTABLE」としています。%% %%Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.%% package mnztech.work.sns import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.media.RingtoneManager import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage class MyFirebaseMessagingService : FirebaseMessagingService() { override fun onNewToken(token: String) { Log.d("MyMessageService", "Refreshed token: $token") } override fun onMessageReceived(remoteMessage: RemoteMessage) { remoteMessage.notification?.let { it -> sendNotification(it) } } private fun sendNotification(message: RemoteMessage.Notification) { val intent = Intent(this, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_MUTABLE) val channelId = getString(R.string.default_notification_channel_id) val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val notificationBuilder = NotificationCompat.Builder(this, channelId) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(message.title) .setContentText(message.body) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Android OS 8以降はチャネル指定が必須 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(channelId, "チャネル説明", NotificationManager.IMPORTANCE_DEFAULT) notificationManager.createNotificationChannel(channel) } notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()) } } ③strings.xmlの編集(ハイライト行を追加) AmazonSNS fcm_default_channel ④AndroidManifest.xmlの編集(ハイライト行を追加) ### デバイストークンの取得 AndroidDeviceとPCを接続して「Run App」を実行します。 「Logcat」に「Current token:」に続きTokenが表示されるので文字列をコピーします。 {{:Aws:SimpleNotificationService:pasted:20230115-130911.png?direct 600x0}} ### AmazonSNSの設定(プラットフォームアプリケーションの作成) ①AmazonSNSコンソールから「プラットフォームアプリケーションの作成」を選択します。 {{:Aws:SimpleNotificationService:pasted:20230115-131432.png?direct 600x0}} ①以下の情報を入力し「プラットフォームアプリケーションの作成」をクリックします。 ・アプリケーション名:好きな名前 ・プッシュ通知プラットフォーム:Firebase Cloud Messaging(FCM) ・APIキー:[[InfrastructureConstruction:Google:FirebaseCloudMessaging01|こちら]]で取得したサーバーキーを入力 {{:Aws:SimpleNotificationService:pasted:20230115-131835.png?direct 600x0}} ### AmazonSNSの設定(アプリケーションエンドポイントの作成) ①作成したアプリケーションを開きます。 {{:Aws:SimpleNotificationService:pasted:20230115-132357.png?direct 600x0}} ①「アプリケーションエンドポイントの作成」を選択します。 {{:Aws:SimpleNotificationService:pasted:20230115-132725.png?direct 600x0}} ②以下の情報を入力し「アプリケーションエンドポイントの作成」をクリックします。 ・デバイストークン:[[Aws:SimpleNotificationService:PlatformApplication01#デバイストークンの取得|こちら]]で取得したデバイストークンを入力 {{:Aws:SimpleNotificationService:pasted:20230115-132951.png?direct 600x0}} ②デバイストークンが追加されます。 {{:Aws:SimpleNotificationService:pasted:20230115-133334.png?direct 600x0}} ### 動作確認 ①メッセージをPushするエンドポイントを選択し「メッセージの発行」を選択します。 {{:Aws:SimpleNotificationService:pasted:20230115-133706.png?direct 600x0}} ②以下の情報を入力し「メッセージの発行」をクリックします。 ・メッセージの構造:配信プロトコルごとにカスタムペイロード ・エンドポイントに送信するメッセージ本文:今回は[[https://docs.aws.amazon.com/ja_jp/sns/latest/dg/sns-send-custom-platform-specific-payloads-mobile-devices.html|こちら]]を例に、以下の通りにしています。 { "GCM":"{ \"notification\": { \"body\": \"Sample message for Android or iOS endpoints\", \"title\":\"TitleTest\" } }" } {{:Aws:SimpleNotificationService:pasted:20230115-134015.png?direct 600x0}} ③スマホの画面を見ると・・・インストールしたアプリにプッシュ通知きたー! {{:Aws:SimpleNotificationService:pasted:20230115-135614.png?direct 600x0}} {{tag>AWS SNS}}