首先添加權限android
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
Android 6.0以後使用device.getType()來判斷手機是否插入耳機或者鏈接藍牙耳機ui
private boolean checkIsWired() { AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { AudioDeviceInfo[] devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS); for (AudioDeviceInfo device : devices) { int deviceType = device.getType(); if (deviceType == AudioDeviceInfo.TYPE_WIRED_HEADSET || deviceType == AudioDeviceInfo.TYPE_WIRED_HEADPHONES || deviceType == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP || deviceType == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) { return true; } } } else { return audioManager.isWiredHeadsetOn() || audioManager.isBluetoothScoOn() || audioManager.isBluetoothA2dpOn(); } return false; }