본문 바로가기
Android

API Level 33 에서 Notification 이 안뜰때..

by 들풀민들레 2023. 3. 20.
본 글은 [Do it! 깡샘의 안드로이드 앱 프로그래밍 with 코틀린] 의 인강의 질문에 답을 하기 위해서 작성되었습니다.

 

 

책의 모든 내용을 저자 직강으로 진행한 강의는 ssamz.com 에서 들으실 수 있습니다.

 

 

API Level 33 버전이 되면서 Notification 에 퍼미션이 요구됩니다.

AndroidManifest.xml 파일에 아래의 퍼미션이 선언되어 있어야 합니다.

 

android.permission.POST_NOTIFICATIONS

또한 API Level 33 이상에서는 퍼미션 체크및 퍼미션 요구가 되어야 합니다.

 

val permissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestMultiplePermissions()
) {
    if (it.all { permission -> permission.value == true }) {
        noti()
    } else {
        Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show()
    }
}
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    if (ContextCompat.checkSelfPermission(
            this,
            "android.permission.POST_NOTIFICATIONS"
        ) == PackageManager.PERMISSION_GRANTED
    ) {
        noti()
    } else {
        permissionLauncher.launch(
            arrayOf(
                "android.permission.POST_NOTIFICATIONS"
            )
        )
    }
}else {
    noti()
}

위의 코드에서 noti() 함수는 Notification 을 띄우기 위한 개발자 함수입니다.

 

fun noti(){
    val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager

    val builder: NotificationCompat.Builder
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        // 26 버전 이상
        val channelId="one-channel"
        val channelName="My Channel One"
        val channel = NotificationChannel(
            channelId,
            channelName,
            NotificationManager.IMPORTANCE_DEFAULT
        ).apply {
            // 채널에 다양한 정보 설정
            description = "My Channel One Description"
            setShowBadge(true)
            val uri: Uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            val audioAttributes = AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build()
            setSound(uri, audioAttributes)
            enableVibration(true)
        }
        // 채널을 NotificationManager에 등록
        manager.createNotificationChannel(channel)
        // 채널을 이용하여 builder 생성
        builder = NotificationCompat.Builder(this, channelId)
    }else {
        // 26 버전 이하
        builder = NotificationCompat.Builder(this)
    }
    //생략...............

    
}

 

 

책의 모든 내용을 저자 직강으로 진행한 강의는 ssamz.com 에서 들으실 수 있습니다.