Android Jetpack - Notification

강보훈·2021년 11월 28일
0

Android Jetpack

목록 보기
3/3

개요

  • 앱이 UI 외부에 표시하는 메세지
  • 알림을 탭하여 열거나 특정 작업을 수행 가능

종류

  1. 상태표시줄에 아이콘으로 표시
  2. 알림 창에 표시
  3. 헤드업 알림 - Android 5.0부터 가능
  4. 잠금 화면 - Android 5.0부터 가능
  5. 앱 아이콘 배지 - Android 8.0(API 26이상)부터 가능

사용방법

  • 우선 가장 기본적인 텍스트만 던져주는 알람

    val channelID = "CHANNELID"
    
            val notificationChannel = NotificationChannel(
                channelID,
                "TestChannelName",
                NotificationManager.IMPORTANCE_DEFAULT
            )
    
            val builder = NotificationCompat.Builder(this, channelID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentTitle("Title")
                .setContentText("ContentText")
    
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(notificationChannel)
    
            notificationManager.notify(
                1, // 해당 알림의 고유 ID
                builder // 표시할 알림
                    .setContentTitle("title")
                    .setContentText("content")
                    .build()
            )
    1. 알람을 관리할 채널을 만들고 매니저에 등록을 한다.
    2. 알람 빌더를 만들고 각종 속성을 정해서 build()하면 알람이 만들어진다.
    3. 매니저에게 알람 고유 아이디와 알람을 넘겨주고 notify()하면 알람이 나타난다.
  • 알람을 눌렀을 때 특정 Activity로 이동 및 알람 삭제

    val intent = Intent(this, NextActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_CLEAR_TASK // 앱 스택 관련처리 부분 굳이 없어도 작동은 함
            }
    
            val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    
            notificationManager.notify(
                1, // 해당 알림의 고유 ID
                builder // 표시할 알림
                    .setContentTitle("title")
                    .setContentIntent(pendingIntent)
                    .setContentText("content")
                    .setAutoCancel(true)
                    .build()
            )
  • 알람에 버튼 추가하기

    • 총 3개까지 버튼 추가가 가능하다.
    • 작업 버튼은 알림을 탭한 경우 실행될 작업과 중복되지 않아야함
    • BroadCast를 사용해서 백그라운드에서 작업을 실행할 수 있다.
    • 미디어 컨트롤도 가능하다. 참고
     val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
      val action = NotificationCompat.Action.Builder(R.drawable.ic_launcher_foreground, "TestAction", pendingIntent).build()
    
            notificationManager.notify(
                1, // 해당 알림의 고유 ID
                builder // 표시할 알림
                    .setContentTitle("title")
                    .addAction(action)
                    .setContentText("content")
                    .setAutoCancel(true)
                    .build()
            )
profile
신입 안드로이드 개발자입니다!

0개의 댓글