안드로이드/Java

[안드로이드][Java] 알림(Notification) 구현

sinw212 2023. 2. 22. 16:27

알림의 기본 구성

  • NotificationManager : 알림을 시스템에 발생시키는 SystemService
  • Notification : 알림 구성 정보를 가지는 객체
  • NotificationCompat.Builder : 알림을 다양한 정보로 생성
  • NotificationChannel : 알림의 관리 단위 (Android Oreo부터 추가)

결국, Notification 객체에 각종 정보를 담고 이 객체를 NotificationManager로 시스템에 등록 후, getSystemService() 함수를 이용하여 NotificationManager를 얻음

//NotificationManager 객체 획득 (Java)
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//NotificationManager 객체 획득 (Kotlin)
val notificationManager = getSystem.Service(NOTIFICATION_SERVICE) as NotificationManager

 

알림 채널

변경) deprecated 변경 내용으로 인해, 아래 '기존' 내용은 참고만 하시길 바랍니다.

notifyBuilder = new NotificationCompat.Builder(Context context) < deprecated

 

알림 만들기  |  Android 개발자  |  Android Developers

알림 만들기 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 알림은 사용 중이 아닌 앱의 이벤트에 관한 짧고 시기적절한 정보를 제공합니다. 이 페이지에서

developer.android.com

위 Android API 문서에 따르면, Channel ID는 API 26 하위버전에서 무시하도록 변경

"Notice that the NotificationCompat.Builder constructor requires that you provide a channel ID. This is required for compatibility with Android 8.0 (API level 26) and higher, but is ignored by older versions."

 

 

기존) 참고용 (사용X)

Android 8.0 (API 26)

  • 모든 알림을 채널에 할당해야함. 그렇지 않으면 알림이 표시되지 않음
  • NotificationChannel
    • Notification 객체는 직접 생성되지 않고, NotificationCompat.Builder로 생성
    • Android O (API 26)부터는 NotificationChannel 개념이 추가되면서, NotificationChannel에 의해 Builder를 생성하도록 변경

Android 7.1 (API 25) 이하

  • 사용자가 앱별로만 알림을 관리할 수 있음
  • NotificationCompat.Builder
    • Builder에 각종 setter 함수를 사용하여 알림의 구성 정보를 명시 후, Notification을 만들고 NotificationManager로 알림 발생
//...
NotificationCompat.Builder notifyBuilder;
if(Builder.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "EMERGENCY", NotificationManager.IMPORTANCE_HIGH);
    //...
    notifyBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
    		.setSmallIcon(R.drawable.~)
         	.// );
} else {
	notifyBuilder = new NotificationCompat.Builder(this)
    		.setSmallIcon(R.drawable.~)
          	.setPriority(NotificationCompat.PRIORITY_HIGH)
                .setDefaults(NotificationCompat.DEFAULT_SOUNT)
                .// );
}

 

 

알림의 중요도

Android 8.0 이상에서는 채널을 통해 알림의 중요도를 지정할 수 있으며, 중요도 설정은 채널에 게시되는 모든 알림의 interruption 수준에 영향을 미침

중요도 수준

  • 긴급 : 알림음이 울리며, 헤드업 알림으로 표시
  • 높음 : 알림음이 울림
  • 중간 : 알림음 없음
  • 낮음 : 알림음도 없고, 상태 표시줄에 표시되지도 않음

Android API 26 이상 : NotificationChannel 생성자에서 지정

  • 단계 : NONE(0) - MIN(1) - LOW(2) - DEFAULT(3) - HIGH(4)

Android API 25 이하 : setPriority() 함수를 이용하여 설정

  • 각각의 notification에 설정하며, priority 상수값을 매개변수로 넣음 (NotificationCompat 클래스 내부)