(Android/System) Android 12+ 알림 채널 설정 및 권한 요청


1. 알림 채널이란?

Android 8.0(API 26)부터 모든 알림은 채널에 속해야 합니다. 사용자는 채널 단위로 소리, 진동, 중요도, 표시 여부를 설정에서 직접 제어합니다.

앱
 ├─ 채널: 채팅 메시지  (중요도 높음, 소리 O)
 ├─ 채널: 프로모션     (중요도 낮음, 소리 X)
 └─ 채널: 시스템 공지  (중요도 보통)

채널을 만든 뒤에는 앱이 중요도/소리를 바꿀 수 없습니다. 사용자가 설정에서 바꿀 수만 있습니다. 처음 만들 때 신중하게 설계하세요. (바꾸려면 새 채널 ID를 만들거나 앱 재설치 필요)


2. 채널 생성

object NotificationChannels {
    const val CHAT = "chat_messages"
    const val PROMO = "promotions"

    fun create(context: Context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return

        val manager = context.getSystemService(NotificationManager::class.java)

        val chat = NotificationChannel(CHAT, "채팅 메시지", NotificationManager.IMPORTANCE_HIGH).apply {
            description = "새 메시지가 도착했을 때 알려줍니다"
            enableVibration(true)
            setShowBadge(true)
        }
        val promo = NotificationChannel(PROMO, "혜택/이벤트", NotificationManager.IMPORTANCE_LOW).apply {
            description = "할인과 이벤트 소식"
        }
        manager.createNotificationChannels(listOf(chat, promo))     // 이미 있으면 무시됨 (재생성 안전)
    }
}

// Application.onCreate()에서 호출
class MyApp : Application() {
    override fun onCreate() { super.onCreate(); NotificationChannels.create(this) }
}
중요도 동작
IMPORTANCE_HIGH 소리 + 헤드업 알림
IMPORTANCE_DEFAULT 소리
IMPORTANCE_LOW 소리 없음, 상태바 표시
IMPORTANCE_MIN 상태바에도 최소 표시
IMPORTANCE_NONE 알림 차단

3. 알림 표시

fun showMessage(context: Context, title: String, text: String) {
    val tapIntent = PendingIntent.getActivity(
        context, 0, Intent(context, ChatActivity::class.java), PendingIntent.FLAG_IMMUTABLE
    )
    val notification = NotificationCompat.Builder(context, NotificationChannels.CHAT)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle(title)
        .setContentText(text)
        .setContentIntent(tapIntent)
        .setAutoCancel(true)                                  // 탭하면 사라짐
        .setPriority(NotificationCompat.PRIORITY_HIGH)        // Android 7 이하용
        .build()

    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PERMISSION_GRANTED
        || Build.VERSION.SDK_INT < 33) {
        NotificationManagerCompat.from(context).notify(System.currentTimeMillis().toInt(), notification)
    }
}

4. Android 13(API 33) 알림 권한

Android 13부터 알림을 보내려면 POST_NOTIFICATIONS 런타임 권한이 필요합니다.

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
private val permissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
    if (granted) onNotificationEnabled() else onNotificationDenied()
}

fun requestNotificationPermission() {
    if (Build.VERSION.SDK_INT < 33) return                    // 이전 버전은 권한 불필요

    when {
        hasPermission() -> onNotificationEnabled()
        shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS) -> showRationaleDialog()
        else -> permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
    }
}

5. 언제 요청할까 — UX 원칙

❌ 앱을 처음 실행하자마자 권한 창 → 이유를 모르는 사용자는 거부
✅ 알림이 필요한 순간(예: 알림 켜기 버튼, 주문 완료 직전)에 맥락과 함께 요청
// 1) 먼저 이유를 설명하는 화면/다이얼로그
// 2) "허용" 누르면 시스템 권한 창 호출
// 3) 거부 시에도 앱 사용은 가능하게 + 나중에 설정에서 켜는 경로 제공

사용자가 두 번 거부하면 시스템이 더 이상 권한 창을 띄우지 않습니다. 이때는 설정 화면으로 안내합니다.


6. 설정 화면으로 이동

// 앱의 알림 설정 화면
fun openNotificationSettings(context: Context) {
    val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
        .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
    context.startActivity(intent)
}

// 특정 채널의 설정 화면
val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
    .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
    .putExtra(Settings.EXTRA_CHANNEL_ID, NotificationChannels.PROMO)

현재 상태 확인:

val enabled = NotificationManagerCompat.from(context).areNotificationsEnabled()
val channelImportance = manager.getNotificationChannel(CHAT)?.importance   // NONE이면 채널이 꺼진 것

7. 채널 그룹

채널이 많을 때 설정 화면에서 묶어서 보여줍니다.

val group = NotificationChannelGroup("social", "소셜")
manager.createNotificationChannelGroup(group)

val chat = NotificationChannel(CHAT, "채팅", IMPORTANCE_HIGH).apply { this.group = "social" }

8. 채널 설계 팁


9. 정리



Related Posts