有人可以教我如何查明蓝牙是否已连接到其他设备(手机、耳机等)
我不知道有什么方法可以获取当前连接的设备列表,但您可以使用 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);
}
}
}
获取当前连接的设备:
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
我认为 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());
}
}
谢谢:)