AudioManager.isWiredHeadsetOn()方法已从 api 级别 14 中弃用,我们现在如何检测是否连接了有线耳机?
问问题
12802 次
6 回答
22
这是我的解决方案:
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;
}
于 2017-08-17T03:57:42.577 回答
21
文档的弃用消息指出:
仅用于检查是否连接了耳机。
所以我想继续使用它来检查是否连接了有线耳机是可以的,但不能检查音频是否被路由到它或通过它播放。
于 2013-01-18T15:03:12.283 回答
11
试试这个解决方案。它在我的情况下工作。可能这对你有帮助!
IntentFilter iFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
Intent iStatus = context.registerReceiver(null, iFilter);
boolean isConnected = iStatus.getIntExtra("state", 0) == 1;
于 2014-11-20T06:24:32.883 回答
0
它对我有用:
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");
}
于 2019-10-04T22:20:29.130 回答
0
IntentFilter iFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
Intent iStatus = context.registerReceiver(null, iFilter);
boolean isConnected = iStatus.getIntExtra("state", 0) == 1;
我知道这段代码可以在哪个andorid平台版本上使用。它在 Android 8 上对我不起作用。结果 iStatus 为空。
于 2020-07-15T01:12:56.570 回答
-1
我们必须使用广播接收器来查找蓝牙连接的状态。
这是一个很好的例子
于 2014-03-25T08:11:41.813 回答