Android Studio 4.2.2
Android SDK 28
Kotlin 1.5.21
알림 (Notification)
정의
사용자에게 정보를 전달하기 위해 앱 UI 외부에 표시하는 메시지. 알림을 탭하여 앱을 열거나, 알림에서 바로 특정 작업을 실행할 수 있음. (android developer)
예
알림 만들기
알림 채널 생성
SDK 버전이 26 이상이라면 반드시 알림 채널을 생성해주어야 한다.
private val context: Context
private val importantChannelId = "중요도 높은 채널 아이디"
private val unimportantChannelId = "중요도 낮은 채널 아이디"
private val channelName = "알림 채널 이름"
private fun createNotificationChannel(isImportant: Boolean = true): NotificationManager {
val importance =
if (isImportant) NotificationManager.IMPORTANCE_HIGH // 중요도 긴급. 알림음이 울리며 헤드업 알림으로 표시됨
else NotificationManager.IMPORTANCE_MIN // 중요도 낮음. 알림음이 없고 상태 표시줄에 표시되지 않음
val channel = NotificationChannel(
if (isImportant) importantChannelId else unimportantChannelId,
channelName,
importance
)
// 알림 채널 등록
val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
return notificationManager
}
알림 중요도에 따른 알림 채널을 생성할 수 있는 메소드이다.
알림 띄우기
private val context: Context
private val appIcon = R.drawable.app_logo
fun showChatNotification() {
val manager = createNotificationChannel()
val notificationId = 1
// 알림 클릭 시 이동하고자 하는 액티비티
val notificationIntent = Intent(context, MainActivity::class.java).apply {
// 기존 액티비티 스택 초기화 및 새로운 테스크로 시작하는 플래그
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
/* 인텐트에 넣을 정보 있다면 넣기
* ex) putExtra("data", 123)
* */
}
val notification = Notification.Builder(context, importantChannelId)
.setSmallIcon(appIcon) // 알림에 표시될 아이콘. 주로 앱 아이콘 사용
.setContentTitle("알림 제목")
.setContentText("알림 내용")
.setContentIntent(
PendingIntent.getActivity(
context,
notificationId, // requestCode
notificationIntent,
// requestCode가 같은 PendingIntent가 이미 존재 시, 기존 PendingIntent cancel 후 다시 생성
PendingIntent.FLAG_CANCEL_CURRENT
)
)
// VISIBILITY_PUBLIC: 알림의 전체 콘텐츠 표시 (잠금 화면 공개 상태 설정)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setAutoCancel(true) // 알림 클릭 시 노티에서 사라지게 하기
.setShowWhen(true) // 알림 온 시간 보여주기
.build()
// 알림 띄우기
manager.notify(notificationId, notification)
}
Notification
Notification.Builder()로 원하는 알림을 생성한다.
manager.notify()에서 알림의 아이디(notificationId)는 반드시 설정해야 하는데, 이 아이디는 알림간 구분에 사용된다. 아이디가 같은 알림이 여러개 띄워졌을 경우, 가장 마지막 알림만 표시되고 아이디가 다를 경우 같은 앱이더라도 여러 알림으로 표시된다.
PendingIntent
알림을 클릭했을 때 동작은 setContentIntent()로 정의한다. 이때 PendingIntent를 사용한다. PendingIntent는 이름 뜻 그대로(pending + intent) 어떤 일이 있기 전까지 대기하는 인텐트이다. 어떤 작업을 요청할지 미리 정의하고, 특정 시점에 요청을 하도록 하는 인텐트인 것이다.
PendingIntent의 getActivity() 메소드에 마지막 인자로 flag가 들어가는데, PendingIntent에 대한 설정을 해준다고 이해하면 편하다. flag는 총 6가지이다.
더 알아보기
Notification.Builer()의 여러 알림 세팅 관련 메소드가 궁금하다면? Notification 안드로이드 공식문서
PendingIntent를 더 알아보고 싶다면? PendingIntent 안드로이드 공식문서
'Android' 카테고리의 다른 글
[Android] 직접 만든 안드로이드 프로젝트 템플릿 (0) | 2021.11.18 |
---|---|
[Android] 권한 확인 및 요청 (0) | 2021.11.15 |
[Android] 액티비티 화면전환 애니메이션 (0) | 2021.11.12 |
[Android] 툴바(앱바) 사용하기 (0) | 2021.11.09 |
[Android] 암시적 인텐트 활용하기 (0) | 2021.11.03 |