gpt4 book ai didi

android - 以编程方式使用蓝牙连接两个 Android 设备

转载 作者:太空宇宙 更新时间:2023-11-03 11:19:50 24 4
gpt4 key购买 nike

我正在做一个蓝牙项目,我想在其中使用蓝牙编程连接两个设备。

我正在遵循 tf developer.android.com 的指南和代码。有人可以帮我解决这个问题吗?这是我试过的代码。

谁能告诉我构造函数从哪里接收设备对象?

private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;

<!-- can anyone tell me from where device object comes here --!>
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;

// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}

public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();

try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}

// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket);
}

/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}


Thanks inadvance

最佳答案

这是我完成任务的一些代码。

    /**
* Searches the list of paired devices for the device. Returns
* if found, throws Exception otherwise.
*
* @param sTargetDeviceName
* @return BluetoothDevice
*/
private BluetoothDevice findDevice(String sTargetDeviceName)
throws Exception {

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

Set<BluetoothDevice> devices = adapter.getBondedDevices();

for (BluetoothDevice device : devices) {

String sDeviceName = device.getName().trim();

if (sDeviceName.startsWith(sTargetDeviceName)) {
return device;
}
}

throw new Exception("Device " + sTargetDeviceName + " not found");
}

要使用上面的代码,设备必须已经配对。

请参阅文档:

http://developer.android.com/guide/topics/wireless/bluetooth.html

特别是“查找设备”部分。

关于android - 以编程方式使用蓝牙连接两个 Android 设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10161382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com