0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

プッシュ通知のAndroid側の実装

Last updated at Posted at 2025-03-15

最近プッシュ通知処理関連のトラブルがありましたので、改めてAndroidで行う通知の実装をまとめる。

  • Firebaseから発行したgoogle-services.json を app/ フォルダに内包させる
buildscript {
    dependencies {
        classpath 'com.google.gms:google-services' // バージョンは最新のものを使用
    }
    repositories {
        google()
    }
}
dependencies {
    implementation 'com.google.firebase:firebase-bom'
    implementation 'com.google.firebase:firebase-messaging-ktx'
    // バージョンは最新のものを使用
}

プロジェクトレベル、アプリレベルのgradleに上記依存関係を追加します。

<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>

<!-- 通知の権限 (Android 13+) -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

Manifestにはサービスを登録する。OS13からは通知許可がいるので、権限も追加する。

class MyFirebaseMessagingService : FirebaseMessagingService() {
    
    // 通知を受信したときの処理
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        remoteMessage.notification?.let {
            sendNotification(it.title ?: "通知がきました。", it.body ?: "メッセー")
        }
    }

    // 新しいトークンが生成されたときの処理
    override fun onNewToken(token: String) {
        Log.d("FCM", "新しいトークン: $token")
        // トークンをサーバーに送信する
    }

    // 通知を作成して表示する
    private fun sendNotification(title: String, messageBody: String) {
        val channelId = "default_channel"
        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        }
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)

        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, "Default Channel", NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
        }
        notificationManager.notify(0, notificationBuilder.build())
    }
}

onMessageReceived()は通知を受け取った時に走る処理です。
onNewToken()新しいトークンが発行された時に呼ばれます。トークンは定期的に変わることがあるため、サーバーに最新のトークンを送る処理を入れます。
sendNotification()通知を作成、表示させます。上記はサンプルコードで、カスタムすることで任意の通知をユーザーに表示させます。sendNotification()onMessageReceived()内で呼び出すと、アプリがフォアグラウンドの時にも通知を表示できます。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?