개발일지

Android in A..Z - Notification 본문

Android (안드로이드)

Android in A..Z - Notification

강태종 2020. 7. 27. 00:59

채널 만들기

Android O 이상에서 Notification을 생성하기 위해서는 Notification Channel을 만들어야 한다.

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val NOTIFICATION_CHANNEL_ID = "id"
    val NOTIFICATION_CHANNEL_NAME = "name"
    val NOTIFICATION_IMPORTANCE = NotificationManager.IMPORTANCE_DEFAULT
    
    val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NOTIFICATION_IMPORTANCE)

    val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    manager.createNotificationChannel(channel)
}

 

기본 알림 만들기

val ID = "id"
val builder = NotificationCompat.Builder(context, ID)
  .setSmallIcon(R.drawable.ic_baseline_android_24)

 

알림에 내용 넣기

val ID = "id"
val builder = NotificationCompat.Builder(context, ID)
  .setSmallIcon(R.drawable.ic_baseline_android_24)
  .setContentTitle("Title")
  .setContentText("Text")

 

긴 내용 알림 만들기

val ID = "id"
val builder = NotificationCompat.Builder(context, ID)
  .setSmallIcon(R.drawable.ic_baseline_android_24)
  .setStyle(NotificationCompat.BigTextStyle().bigText("Long text"))

 

알림 클릭 했을 때 처리하기

val intent = Intent(context, MainActivity::class.java).apply {
  flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

val pending = PendingIntent.getActivity(context, 0, intent, 0)

val ID = "id"
val builder = NotificationCompat.Builder(context, ID)
  .setSmallIcon(R.drawable.ic_baseline_android_24)
  .setContentIntent(pending)

 

알림에 액션 추가하기

val intent = Intent(context, MainActivity::class.java).apply {
  flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

val pending = PendingIntent.getActivity(context, 0, intent, 0)

val ID = "id"
val builder = NotificationCompat.Builder(context, ID)
  .setSmallIcon(R.drawable.ic_baseline_android_24)
  .addAction(R.drawable.ic_baseline_adb_24, "Action", pending)

 

알림 표시

val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(1, builder.build())

 

'Android (안드로이드)' 카테고리의 다른 글

Android in A..Z - TextInputLayout  (0) 2021.01.20
Android in A..Z - Glide  (0) 2020.11.07
Android in A..Z - Widget  (0) 2020.08.09
Android in A..Z - Handler  (0) 2020.07.28
Android in A..Z - Activity Lifecycle  (0) 2020.07.28
Comments