【发布时间】:2012-04-18 14:58:24
【问题描述】:
谁能教我如何确定蓝牙是否连接到其他设备(手机、耳机等)
【问题讨论】:
标签: android bluetooth find connect out
谁能教我如何确定蓝牙是否连接到其他设备(手机、耳机等)
【问题讨论】:
标签: android bluetooth find connect out
我不知道获取当前连接设备列表的任何方法,但您可以使用 ACL_CONNECTED 意图监听新连接: http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_ACL_CONNECTED
这个意图包括一个额外的字段,用于连接的远程设备。
在 Android 上,所有蓝牙连接都是 ACL 连接,因此注册此 Intent 将获得所有新连接。
所以,你的接收器看起来像这样:
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);
}
}
}
【讨论】:
On Android, all Bluetooth connections are ACL connections 你确定吗?有那个链接吗?!
获取当前连接的设备:
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());
}
}
谢谢:)
【讨论】: