首先添加权限
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
Android 6.0之后使用device.getType()来判断手机是否插入耳机或者连接蓝牙耳机
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;
}