Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to the deprecated AudioManager.isWiredHeadsetOn?

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

like image 658
Bjarke Freund-Hansen Avatar asked Jan 18 '13 15:01

Bjarke Freund-Hansen


People also ask

What is an audio manager?

Audio Manager in android is a class that provides access to the volume and modes of the device. Android audio manager helps us adjust the volume and ringing modes of devices based on our requirements. The modes that are well known to us, that are Ringing, Vibration, Loud, Silent, etc.


3 Answers

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;
}
like image 118
Bingerz Avatar answered Sep 20 '22 21:09

Bingerz


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.

like image 22
Raghav Sood Avatar answered Sep 19 '22 21:09

Raghav Sood


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;
like image 11
AlexS Avatar answered Sep 21 '22 21:09

AlexS