有人可以教我如何确定蓝牙是否连接到其他设备(手机、耳机等)
问问题
8792 次
3 回答
4
我不知道获取当前连接设备列表的任何方法,但您可以使用 ACL_CONNECTED 意图监听新连接:http: //developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_ACL_CONNECTED
此意图包括一个带有连接的远程设备的额外字段。
在 Android 上,所有蓝牙连接都是 ACL 连接,因此注册此意图将为您提供所有新连接。
所以,你的接收器看起来像这样:
public class ReceiverBlue extends BroadcastReceiver {
public final static String CTAG = "ReceiverBlue";
public Set<BluetoothDevice> connectedDevices = new HashSet<BluetoothDevice>();
public void onReceive(Context ctx, Intent intent) {
final BluetoothDevice device = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
if (BluetoothDevice.ACTION_ACL_CONNECTED.equalsIgnoreCase( action ) ) {
Log.v(CTAG, "We are now connected to " + device.getName() );
if (!connectedDevices.contains(device))
connectedDevices.add(device);
}
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equalsIgnoreCase( action ) ) {
Log.v(CTAG, "We have just disconnected from " + device.getName() );
connectedDevices.remove(device);
}
}
}
于 2012-04-04T23:48:29.680 回答
1
要获取当前连接的设备:
val adapter = BluetoothAdapter.getDefaultAdapter() ?: return // null if not supported
adapter.getProfileProxy(context, object : BluetoothProfile.ServiceListener {
override fun onServiceDisconnected(p0: Int) {
}
override fun onServiceConnected(profile: Int, profileProxy: BluetoothProfile) {
val connectedDevices = profileProxy.connectedDevices
adapter.closeProfileProxy(profile, profileProxy)
}
}, BluetoothProfile.HEADSET) // or .A2DP, .HEALTH, etc
于 2018-11-01T19:49:18.817 回答
0
我认为 getBondedDevices() 会帮助你:)
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
谢谢 :)
于 2012-04-04T21:30:58.977 回答