我知道如何获取配对设备的列表,但如何判断它们是否已连接?
这必须是可能的,因为我看到他们在我的手机的蓝牙设备列表中列出,它说明了他们的连接状态。
发布于 2016-12-16 17:47:57
在我的用例中,我只想看看VoIP应用程序是否连接了蓝牙耳机。下面的解决方案对我很有效。
Kotlin:
fun isBluetoothHeadsetConnected(): Boolean {
val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
return (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled
&& mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED)
}
Java:
public static boolean isBluetoothHeadsetConnected() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()
&& mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;
}
当然,您需要蓝牙权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
发布于 2013-08-02 07:45:12
由于某些原因,Android Studio无法解析BluetoothAdapter.ACTION_ACL_CONNECTED。也许它在Android 4.2.2中被弃用了?
以下是Skylarsutton代码的修改(非常感谢Skylarsutton for his answer。)注册代码是相同的;接收者代码略有不同。我在一个服务中使用它,该服务更新应用程序的其他部分引用的蓝牙连接标志。
public void onCreate() {
//...
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(BTReceiver, filter);
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Do something if disconnected
Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
}
//else if...
}
};
发布于 2018-09-11 22:02:22
此代码适用于耳机配置文件,可能也适用于其他配置文件。
首先,您需要提供一个配置文件侦听器(Kotlin代码):
private val mProfileListener = object : BluetoothProfile.ServiceListener {
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
if (profile == BluetoothProfile.HEADSET)
mBluetoothHeadset = proxy as BluetoothHeadset
}
override fun onServiceDisconnected(profile: Int) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null
}
}
}
然后在检查蓝牙时:
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}
调用onSeviceConnected需要一些时间。之后,您可以从以下位置获取已连接耳机设备的列表:
mBluetoothHeadset!!.connectedDevices
https://stackoverflow.com/questions/4715865
复制相似问题