已弃用的AudioManager.isWiredHeadsetOn的替代方案?

Bja*_*sen 8 android android-audiomanager

方法AudioManager.isWiredHeadsetOn()已从API级别14弃用,我们现在如何检测是否连接了有线耳机?

Rag*_*ood 18

文档的弃用消息指出:

仅用于检查耳机是否已连接.

所以我想可以继续使用它来检查有线耳机是否已连接,但不能检查音频是否被路由到它或通过它播放.

  • 我想答案就是这么简单.我发现弃用一个方法很困惑,如果它没有真正弃用,它只是稍微改变了目的.不管怎样,谢谢.:) (2认同)

Bin*_*erz 17

这是我的解决方案:

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 (int i = 0; i < devices.length; i++) {
            AudioDeviceInfo device = devices[i];

            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;
Run Code Online (Sandbox Code Playgroud)

}


Ale*_*exS 7

试试这个解决方案 它在我的情况下工作.可能这对你有所帮助!

IntentFilter iFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
Intent iStatus = context.registerReceiver(null, iFilter);
boolean isConnected = iStatus.getIntExtra("state", 0) == 1;
Run Code Online (Sandbox Code Playgroud)