본문 바로가기

개발 코딩 정보 공유/안드로이드 자바 코틀린

안드로이드 8.0(api26) 알림채널 생성하기 (notification channel)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

안드로이드 api 26(8.0 오레오) 대비 작업 - 알림 채널 생성

 

 

 

 

android oreo / pixabay / knd61

 

 

 

안녕하세요. 안드로이드 api 26(8.0 오레오)에 대비 하여 오늘은 알림 채널 생성을 해보겠습니다.

알림을 채널별로 관리하여 좀더 효율적으로 사용한다는 것인데요. 역시나 너무 귀찮습니다.

 

"Android 8.0 (API 레벨 26)부터 모든 알림을 채널에 할당해야합니다. 

각 채널에 대해 해당 채널의 모든 알림에 적용되는 시각 및 청각 동작을 설정할 수 있습니다. 

그런 다음 사용자는 이러한 설정을 변경하고 앱의 알림 채널을 방해하거나 눈에 띄게할지 결정할 수 있습니다."

 

아래와 같이 작업을 하시면 되는데요. 알림채널의 경우 단 한번만 설정하면 다시 설정할 필요가 없기때문에 

application 객체등에 설정해놓으시면 좋겠네요. 또한 오레오 이하의 버전은 채널설정이 불필요 하므로

' if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) ' 와 같은 버전 확인작업을 통해

방어 하는 코드를 짜야 합니다. 'NotificationChannel'을 생성하고 'NotificationManager' 를 통해 등록해줍니다.

 

*** 이때 CHANNEL_ID 는 notice build 시에 붙여넣는 id 와 동일 값을 넣어야 합니다. 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}
 
cs

 

 

"Android 8.0 (API 레벨 26) 을 타겟팅하는 경우 하나 이상의 알림 채널을 구현해야합니다. 

당신이 경우 targetSdkVersion 앱이 안드로이드 8.0 (API 레벨 26) 이상에서 실행될 때 25 이하로 설정되어, 

그것은 안드로이드 7.1 (API 레벨 25) 이하를 실행 장치는 것 같은 동작합니다."

 

채널을 구현하고 알림을 구현 합니다.

 

1
2
3
4
5
6
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) //CHANNEL_ID 채널에 지정한 아이디
            .setContentTitle("background machine")
            .setContentText("알림입니다")
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentIntent(pendingIntent)
            .setOngoing(true).build();
cs

 

 

 

채널만 생성하면 비교적 간단하게 수정할 수 있습니다.

주의 할 점은 만약 Android 8.0 (API 레벨 26) 을 타겟팅 하고, 

알림채널을 생성하지 않았다면 알림이 정상 동작하지 않고 로그에 오류가 찍히게 됩니다.

이상 Android 8.0 (API 레벨 26) 대비 알림관련 작업이었습니다.

 

 

참고 :

 

"https://developer.android.com/training/notify-user/channels"

"https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder"