Android

안드로이드 방해금지 모드 여부 확인 방법

휴대폰 설정이 방해금지모드일때, 앱은 진동과 소리를 중지해야할 필요가 생긴다.  시스템 설정을 따라가게 하기 위해 방해금지모드인지 여부를 체크 하는 방법과 방해금지모드 일때 권한을 부여하여 방해금지모드를 무시하는 방법에 대해 알아본다.

ANDROID 방해금지 모드 여부 확인 방법

int zenModeValue = Settings.Global.getInt(getContentResolver(), "zen_mode");

방해금지모드 여부를 체크하기 위해 Settings.Global 클래스를 사용한다. “zen_mode” 문자열로 넘겨서 확인이 가능하다.

Settings클래스를 까보면 “zen_mode”로 선언되어 있음을 확인가능하다.

        /**
         * Defines global zen mode.  ZEN_MODE_OFF, ZEN_MODE_IMPORTANT_INTERRUPTIONS,
         * or ZEN_MODE_NO_INTERRUPTIONS.
         *
         * @hide
         */
        @UnsupportedAppUsage
        public static final String ZEN_MODE = "zen_mode";

        /** @hide */
        @UnsupportedAppUsage
        public static final int ZEN_MODE_OFF = 0;
        /** @hide */
        @UnsupportedAppUsage
        public static final int ZEN_MODE_IMPORTANT_INTERRUPTIONS = 1;
        /** @hide */
        @UnsupportedAppUsage
        public static final int ZEN_MODE_NO_INTERRUPTIONS = 2;
        /** @hide */
        @UnsupportedAppUsage
        public static final int ZEN_MODE_ALARMS = 3;

4개의 리턴값을 반환한다. 0은 방해금지모드 OFF 상태이며, 1,2,3은 방해금지모드가 ON 상태이다. 1은 중요한 알림만 받으며, 2의 경우 완전 무음 모드처리이며, 3의 경우 경보만 알린다.

실제 활용가능한 코드 샘플은 다음과 같다.

    private int logZenModeState() {
        int zenModeValue = 0;
        try {
            zenModeValue = Settings.Global.getInt(getContentResolver(), "zen_mode");

            switch (zenModeValue) {

                case 0:
                    Log.e("TAG", "DnD : OFF");
                    break;
                case 1:
                    Log.e("TAG", "DnD : ON - Priority Only");
                    break;
                case 2:
                    Log.e("TAG", "DnD : ON - Total Silence");
                    break;
                case 3:
                    Log.e("TAG", "DnD : ON - Alarms Only");
                    break;
                default:
                    Log.e("TAG", String.format(Locale.getDefault(), "DnD : Some other value in the future? Or obscure mfctr implementation? [%d]", zenModeValue));
            }
        }catch (Settings.SettingNotFoundException e){
            zenModeValue = 0;
        }

        return zenModeValue;
    }

다음은 방해금지모드일때 앱에 권한이 있는지 체크하는 코드이다.

보통의 경우 휴대폰 설정이 방해금지모드일때 특정 앱에서 볼륨을 키우거나 줄일때 오류가 발생하게 되어있다.

    private void setSoundVolume(){
        try {
            //볼륨 저장값 조회
            // 노래 재생완료 후 원래설정으로 변경해야함.
            audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

            //SharedPreferences에 저장된 볼륨값 조회
            SharedPreferences sp = getSharedPreferences(MY_PM_PREF, Activity.MODE_PRIVATE);
            int nVolume = sp.getInt(PM_SET_VOL, 5);

            if(!sp.getBoolean(IS_RINGTONE_SET,false)) {  //벨소리 모드가 아니면
                nCurrentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                //볼륨값 설정
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, nVolume, AudioManager.FLAG_PLAY_SOUND);  //(int)(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)*0.25)  // or *0.75
            }else{
                nCurrentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_RING);
                //볼륨값 설정
                audioManager.setStreamVolume(AudioManager.STREAM_RING, nVolume, AudioManager.FLAG_PLAY_SOUND);  //(int)(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)*0.25)  // or *0.75
            }
        }catch (Exception e){
            //휴대폰이 방해금지 모드일때 오류 발생
            callActivityForPolicyAccessSettings();
        }
    }

오류가 발생할 때 권한 부여를 위한 intent를 호출하였다.

    private void callActivityForPolicyAccessSettings() {
        // Ask the user to grant access
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        try {
            //휴대폰이 방해금지 모드일때 오류 발생
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notificationManager!= null && !notificationManager.isNotificationPolicyAccessGranted()) {
                Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
                startActivity(intent);
            }else{
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && notificationManager!= null && notificationManager.isNotificationPolicyAccessGranted()) {
                    //AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
                    if(audioManager!= null) {
                        audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

AndroidManifest.xml 파일에 권한 부여를 하여야 한다.

<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" /> <!-- 방해금지모드 -->

[참고]
Android: Detect Do Not Disturb status?

[연관]
https://android–examples.blogspot.com/2017/08/android-turn-on-off-do-not-disturb-mode.html

Leave a Reply

error: Content is protected !!