[kotlin] 코틀린으로 푸시 알림 구현하기
안녕하세요! 오늘은 안드로이드 앱에 푸시 알림을 구현하는 방법에 대해 살펴보겠습니다. 코틀린을 사용하여 Firebase Cloud Messaging (FCM)을 통해 푸시 알림을 구현해 보겠습니다.
전제 조건
- 안드로이드 스튜디오가 설치되어 있어야 합니다.
- Firebase 프로젝트가 설정되어 있어야 합니다.
- FCM 의존성이 추가된 안드로이드 프로젝트가 있어야 합니다.
단계별 구현
1. FCM 설정
Firebase 콘솔에서 프로젝트를 생성하고 FCM을 설정합니다. google-services.json
파일을 안드로이드 프로젝트에 추가합니다.
2. 푸시 알림 수신기 생성
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
// 푸시 알림을 받았을 때의 동작 처리
// remoteMessage.notification 에 알림 메시지 데이터가 포함되어 있음
}
override fun onNewToken(token: String) {
super.onNewToken(token)
// FCM 토큰 갱신 시의 처리
}
}
3. AndroidManifest.xml 수정
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
4. 푸시 알림 표시
푸시 알림을 수신한 후, 알림을 표시하는 방법에 대한 처리를 추가합니다.
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.RemoteMessage
class MyFirebaseMessagingService : FirebaseMessagingService() {
// ...
override fun onMessageReceived(remoteMessage: RemoteMessage) {
// ...
remoteMessage.notification?.let {
// 푸시 알림을 표시하는 처리
showNotification(it.title, it.body)
}
}
private fun showNotification(title: String?, message: String?) {
// 알림 채널 생성 (Android 8.0 이상)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel("channelId", "channelName", NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
// 알림 표시
val notificationBuilder = NotificationCompat.Builder(this, "channelId")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(message)
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.notify(0, notificationBuilder.build())
}
}
마치며
이제 코틀린을 사용하여 FCM을 통해 안드로이드 앱에 푸시 알림을 구현하는 방법에 대해 알아보았습니다. 푸시 알림은 사용자와의 소통을 강화하고 사용자 경험을 향상시키는 데 매우 유용합니다. 추가적으로 푸시 알림 데이터 처리, 알림 클릭 시의 동작 처리 등을 고려하여 더 다양한 푸시 알림 기능을 구현할 수 있습니다.