Check whether headphones are plugged in

后端 未结 4 1782
时光说笑
时光说笑 2020-12-14 01:13

I can\'t seem to find a way to know on android if the headphones are plugged in. I found various solutions but they always seem to return false. The only thing that seems to

4条回答
  •  误落风尘
    2020-12-14 01:58

    audioManager.isWiredHeadsetOn() is deprecated as per below code from android.media.AudioManager

    /**
     * Checks whether a wired headset is connected or not.
     * 

    This is not a valid indication that audio playback is * actually over the wired headset as audio routing depends on other conditions. * * @return true if a wired headset is connected. * false if otherwise * @deprecated Use {@link AudioManager#getDevices(int)} instead to list available audio devices. */ public boolean isWiredHeadsetOn() { if (AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADSET,"") == AudioSystem.DEVICE_STATE_UNAVAILABLE && AudioSystem.getDeviceConnectionState(DEVICE_OUT_WIRED_HEADPHONE,"") == AudioSystem.DEVICE_STATE_UNAVAILABLE && AudioSystem.getDeviceConnectionState(DEVICE_OUT_USB_HEADSET, "") == AudioSystem.DEVICE_STATE_UNAVAILABLE) { return false; } else { return true; } }

    so we need to use AudioManager#getDevices method like below

    private boolean isWiredHeadsetOn(){
        AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        AudioDeviceInfo[] audioDevices = audioManager.getDevices(AudioManager.GET_DEVICES_ALL);
        for(AudioDeviceInfo deviceInfo : audioDevices){
            if(deviceInfo.getType()==AudioDeviceInfo.TYPE_WIRED_HEADPHONES
                    || deviceInfo.getType()==AudioDeviceInfo.TYPE_WIRED_HEADSET){
                return true;
            }
        }
        return false;
    }
    

提交回复
热议问题