[kotlin] 알람과 알림(Notification) 사용하기

최근에 Kotlin을 이용하여 안드로이드 앱을 개발하고 계시다면, 사용자에게 시간 또는 이벤트에 대한 알림을 제공해야 할 경우가 있을 것입니다. Kotlin에서는 이러한 알람과 알림을 사용하는 방법을 몇 가지 제공하고 있습니다. 이번 포스트에서는 Kotlin을 사용하여 안드로이드에서 알람과 알림(Notification)을 작성하고 사용하는 방법에 대해 알아보겠습니다.

1. 알람 설정하기

Kotlin을 사용하여 시간 기반으로 알람을 설정하려면 AlarmManager를 사용합니다. 아래의 코드는 AlarmManager를 이용하여 10초 후에 알람을 발생시키는 예시입니다.

val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val alarmIntent = Intent(context, AlarmReceiver::class.java).let { intent ->
    PendingIntent.getBroadcast(context, 0, intent, 0)
}

val triggerTime = SystemClock.elapsedRealtime() + 10000

alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, alarmIntent)

위의 코드에서는 AlarmManager를 이용하여 AlarmReceiver를 통해 알람 수신하도록 설정하고 있습니다. ELAPSED_REALTIME_WAKEUP을 사용하여 상대적인 시간을 지정하였습니다.

2. 알림(Notification) 생성하기

Kotlin으로 알림을 생성하려면 NotificationCompat.Builder를 사용합니다. 아래의 코드는 기본적인 형태의 알림을 생성하는 예시입니다.

val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val name = getString(R.string.channel_name)
    val descriptionText = getString(R.string.channel_description)
    val importance = NotificationManager.IMPORTANCE_DEFAULT
    val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
        description = descriptionText
    }
    notificationManager.createNotificationChannel(channel)
}

val builder = NotificationCompat.Builder(this, CHANNEL_ID)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")

with(NotificationManagerCompat.from(this)) {
    notify(notificationId, builder.build())
}

위의 코드에서는 먼저 NotificationManager를 통해 NotificationChannel을 생성하고, NotificationCompat.Builder를 이용하여 알림을 구성하였습니다. 마지막으로 NotificationManagerCompat를 이용하여 알림을 표시하였습니다.

3. 권한 및 권한 요청

알람과 알림을 사용하기 위해서는 AndroidManifest.xml 파일에 적절한 권한을 추가해야 합니다. 또한, 일부 안드로이드 버전에서는 런타임 시 권한을 요청해야 합니다.

<uses-permission android:name="android.permission.SET_ALARM" />
<uses-permission android:name="android.permission.VIBRATE" />

위의 코드는 알람을 설정하고 진동을 사용하기 위한 권한을 추가한 예시입니다.

알람과 알림을 사용하기 위해 필요한 권한을 추가하고 런타임 시 권한을 확인하도록 코드를 추가해주세요.

안드로이드에서 알람과 알림을 사용하기 위한 Kotlin의 기본적인 방법에 대해 알아보았습니다. 필요에 따라 실제 앱에서 활용할 수 있는 코드로 추가적인 기능을 구현하실 수 있을 것입니다.

참고 자료: Android Developers - Notifications