Alternative to the deprecated AudioManager.isWiredHeadsetOn?

后端 未结 6 1460
暗喜
暗喜 2021-02-13 20:47

The method AudioManager.isWiredHeadsetOn() is deprecated from api level 14, how do we now detect if a wired headset is connected?

6条回答
  •  离开以前
    2021-02-13 20:55

    This is my solution:

    private boolean isHeadsetOn(Context context) {
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    
        if (am == null)
            return false;
    
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return am.isWiredHeadsetOn() || am.isBluetoothScoOn() || am.isBluetoothA2dpOn();
        } else {
            AudioDeviceInfo[] devices = am.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
    
            for (AudioDeviceInfo device : devices) {
                if (device.getType() == AudioDeviceInfo.TYPE_WIRED_HEADSET
                        || device.getType() == AudioDeviceInfo.TYPE_WIRED_HEADPHONES
                        || device.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP
                        || device.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) {
                    return true;
                }
            }
        }
        return false;
    }
    

提交回复
热议问题