Android 외 개발

Android Notification example

Spring-봄 2020. 1. 7. 16:07

Notification을 실행하기 위해서 먼저 Builder를 구성하였습니다.

val notificationBuilder: NotificationCompat.Builder 
       = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .apply {
                setSmallIcon(R.drawable.icon)
                setDefaults(Notification.DEFAULT_ALL)
                setContentTitle(title)
                setContentText(content)
                setAutoCancel(false)
                setWhen(System.currentTimeMillis())
                priority = NotificationCompat.PRIORITY_MAX
                setContentIntent(pendingIntent)
            }

NotificationCompat.Builder(Context context) 의 경우 Deprecated 되었으며, 굳이 Oreo 버전으로 구분하여 사용하지 않 고 NotificationCompat.Builder(Context context, String channelId) 를 사용하면 됩니다.

 

title 과 text 는 표시되는 문구들이며, when 의 경우 시간을 표시 합니다.

setContentIntent 의 경우 Notification을 클릭시 activity 연결이 필요한 경우 사용합니다.

val notificationIntent = Intent(this, MainActivity::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0)

 

주의 점으로는 icon을 생략하게 되면 아래 같이 title 과 text 가 무시되고 "~ 실행중입니다." 라는 Notification 이 발생합니다.

 

 

Android Oreo 이상 버전인 경우 NotificationChannel 구성이 필요합니다.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, 
    NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_NONE).apply {
        description = getString(R.string.app_name)
        lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    }
    notificationManager.createNotificationChannel(notificationChannel)
}

진동 설정을 하지 않아도 진동이 온다면, importance 설정을 NotificationManager.IMPORTANCE_NONE 으로 변경하시면 됩니다.

 

notificationManager.notify(0, notificationBuilder.build())

notification 을 실행하는 코드입니다.

 

Foreground Service 에서 Notification 을 실행하는 경우는 아래와 같이 코드를 생성합니다.

        startForeground(1, notification)

주의점으로 startForeground 시 id 가 0이 되는 경우 실행이 되지 않습니다.

 

추가로 Service를 실행하는 코드는 아래를 참고하세요.

    fun startService() {
        val intent = Intent(this, CardService::class.java)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
    }

 

실행 결과 입니다.

테스트 앱 개발 중 작성한 글이라 NFC 문구가 들어가 있지만, 결과적으로는 정상적으로 동작함을 확인하였습니다.

 

결과