我正在尝试使用Android设备连接到蓝牙设备以检索一些信息。特别是我正在尝试在此UUID上连接蓝牙耳机:
"0000111E-0000-1000-8000-00805F9B34FB"
为此,我正在创建一个套接字,并通过以下方式将其连接到远程设备:
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket
// because mmSocket is final.
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothSocket tmp = null;
mmDevice = device;
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
tmp = device.createRfcommSocketToServiceRecord(UUID_HF);
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
bluetoothAdapter.cancelDiscovery();
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
try {
mmSocket.close();
} catch (IOException closeException) {
Log.e(TAG, "Could not close the client socket", closeException);
}
return;
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
manageMyConnectedSocket(mmSocket);}
当耳机尚未与我的Android设备连接时,它可以正常工作。但是,由于操作系统本身,耳机会自动与我的Android设备连接。在这种情况下,当我执行mmSocket.connect()方法时,它不会返回。我以为Android可能已经自动连接了另一个具有相同UUID的套接字,所以我的那个不起作用。您是否认为这是问题所在?如果是的话,有没有办法关闭我的Android设备和远程蓝牙设备之间的所有插座?也许只是一个困扰我的过程? 预先感谢。
答案 0 :(得分:0)
实际情况是操作系统正在执行配对的设备标准,以节省一些电池,因为搜索过程会消耗大量能量。 由于您已完成搜索,因此应该在配对设备中进行搜索,而不是常规搜索,并且搜索结果应取自 查询配对的设备
在执行设备发现之前,值得查询配对设备的集合以查看所需设备是否已知。为此,请调用getBondedDevices()。这将返回一组代表配对设备的BluetoothDevice对象。例如,您可以查询所有配对的设备,并获取每个设备的名称和MAC地址,如以下代码片段所示:
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
}
}
要启动与蓝牙设备的连接,关联的BluetoothDevice对象所需的全部就是MAC地址,您可以通过调用getAddress()检索该MAC地址。您可以在“连接设备”部分中了解有关创建连接的更多信息。
这是Google的官方文档,涵盖了有关蓝牙的所有详细信息: https://developer.android.com/guide/topics/connectivity/bluetooth