Android Notification

임찬형·2022년 3월 8일
0

Android 기본

목록 보기
5/7

Notification 구성

  1. 작은 아이콘(필수): setSmallIcon()을 통해 설정
  2. 앱 이름: 시스템에서 제공
  3. 타임 스탬프: 시스템에서 제공하나, setWhen()으로 재정의 가능하며 setShowWhen(false)로 숨길 수 있음
  4. 큰 아이콘: setLargeIcon()을 통해 설정
  5. 제목: setContentTitle()을 통해 설정
  6. 텍스트: setContentText()을 통해 설정

+) 추가로 작업 버튼 등을 더할 수 있음

기본 알림 생성

  1. NotificationCompat.Builder를 통해 알림 콘텐츠와 채널 설정.
var builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle(textTitle)
            .setContentText(textContent)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
  1. 채널 생성 및 중요도 설정
    Oreo 버전 이상에서는 Channel 설정 필수.
private fun createNotificationChannel() {
    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
        }
        val notificationManager: NotificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        	notificationManager.createNotificationChannel(channel)
    }
}
    
  1. 알림 탭 작업 설정
    PendinIntent를 setContentIntent()을 통해 등록함.
 val intent = Intent(this, AlertDetails::class.java).apply {
        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    }
    val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)

    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)

+) setAutoCancel(true): 알림 탭 한 경우 자동으로 알림 종료

  1. 알림 표시
    NotificationManagerCompat.notify()를 통해 표시
 with(NotificationManagerCompat.from(this)) {
    notify(notificationId, builder.build())
}

.../

0개의 댓글