Alternative to the deprecated AudioManager.isWiredHeadsetOn?

后端 未结 6 1463
暗喜
暗喜 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;
    }
    
    0 讨论(0)
  • 2021-02-13 20:56
    IntentFilter iFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    Intent iStatus = context.registerReceiver(null, iFilter);
    boolean isConnected = iStatus.getIntExtra("state", 0) == 1;
    

    I do know this code can be used on which andorid platform version. It does not work for me on Android 8. Result iStatus is null.

    0 讨论(0)
  • 2021-02-13 21:00

    It works for me correctly:

    if(context.registerReceiver(null, new IntentFilter(Intent.ACTION_HEADSET_PLUG)).getIntExtra("state", 0)==1){
    //if(audioManager.isWiredHeadsetOn()){
        System.out.println("Headset is wiredOn");
    }
    else{
        System.out.println("Headset is not wiredOn");
    }
    
    0 讨论(0)
  • 2021-02-13 21:09

    The documentation's deprecation message states:

    Use only to check is a headset is connected or not.

    So I guess it is okay to keep using it to check whether or not a wired headset is connected, but not to check whether or not audio is being routed to it or played over it.

    0 讨论(0)
  • 2021-02-13 21:12

    we have to be using broadcast Receivers for finding the status of bluetooth connection.

    Here is a good example

    0 讨论(0)
  • 2021-02-13 21:20

    Try this solution. It's working in my case. May be this helps you!

    IntentFilter iFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    Intent iStatus = context.registerReceiver(null, iFilter);
    boolean isConnected = iStatus.getIntExtra("state", 0) == 1;
    
    0 讨论(0)
提交回复
热议问题