일상, 등산, 개발자 블로그

[Android] 알림(Notification) 볼륨 설정 및 방해금지 권한 부여(not disturb) 본문

개발/Android

[Android] 알림(Notification) 볼륨 설정 및 방해금지 권한 부여(not disturb)

merge-master 2023. 3. 7. 17:30
반응형

Android Device 에서 제공하는 여러 볼륨 중 "알림" 볼륨 설정 하는 방법이다.

private fun setAudioNotificationVolume() {
    try {
        val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
        // 최대 가능 볼륨 (15)
        val maxVolumeNotification = audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION)
        // 현재 볼륨
        val currentVolumeNotification = audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION)

        Log.d("active", "maxVolumeNotification: $maxVolumeNotification")
        Log.d("active", "currentVolumeNotification: $currentVolumeNotification")
        // 50% 볼륨 셋팅
        audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, maxVolumeNotification / 2, 0)

        audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); //벨소리모드로 변경
        audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); //진동모드로 변경
        audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); //무음모드로 변경

    } catch (e : Exception) {
        Log.d("active", "Exception: $e")
        e.printStackTrace()
    }
}

만약 볼륨을 1 => 0 또는 0 => 1 과 같이 볼륨 완전히 끄거나 완전히 끈 상태에서 키는 경우는 별도의 퍼미션이 필요하다.

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

퍼미션 추가

val notificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (!notificationManager.isNotificationPolicyAccessGranted) { 
    this.startActivity(Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS)) 
}

퍼미션을 부여 받으면 볼륨 설정 후 무음모드 설정이 가능하다

val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager

audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); //벨소리모드로 변경
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); //진동모드로 변경
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); //무음모드로 변경
반응형
Comments