我正在尝试在Android智能手机(客户端)与PC上运行的蓝牙应用(服务器)之间建立连接。
以下是客户端的代码段
// if the request has query parameters, `hasQuery` will be set to `true`
var hasQuery = event.request.url.indexOf('?') != -1;
event.respondWith(
caches.match(event.request, {
// ignore query section of the URL based on our variable
ignoreSearch: hasQuery,
})
.then(function(response) {
// handle the response
})
);
以下是服务器代码(使用BlueCover jar)
private void waitForConnection(){ LocalDevice local = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
try {
//tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.d(TAG, "create() failed", e);
e.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
mAdapter.cancelDiscovery();
try {
mmSocket.connect();
}
catch (IOException e) {
//Exception caught
//java.io.IOException: read failed, socket might closed or timeout, read ret: -1
...
}
...
}
我已阅读了几条建议将UUID更改为“00001101-0000-1000-8000-00805F9B34FB”的链接,我已经尝试过了。我还尝试使用createInsecureRfcommSocketToServiceRecord创建一个不安全的套接字,它仍然失败,结果相同。
下面是IOException堆栈跟踪
StreamConnectionNotifier notifier;
StreamConnection connection = null;
try {
local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);
String uuidstr = "00001101-0000-1000-8000-00805F9B34FB";
String uuid_wo_space = uuidstr.replaceAll("-", "");
String url = "btspp://localhost:" + uuid_wo_space + ";authenticate=false;encrypt=false;name=RemoteBluetooth";
notifier = (StreamConnectionNotifier) Connector.open(url);
}
catch (Exception e) {
e.printStackTrace();
return;
}
// waiting for connection
while(true) {
try {
connection = notifier.acceptAndOpen();
Thread processThread = new Thread(new ProcessConnectionThread(connection));
processThread.start();
}
catch(Exception e) {
e.printStackTrace();
return;
}
}
答案 0 :(得分:1)
很抱歉写了一个新答案,但这样信息比答复更明显。这是我的设备的UUID示例列表:
UUID: 0000xxxx-0000-1000-8000-00805f9b34fb
i xxxx Status Mode
0 110a N.A.
1 1105 Connected Serial Port Protocol (SPP)
2 1106 Connected File transfer (FTP)
3 1116 N.A.
4 112d Connected Remote SIM mode
5 112f Connected Phone book request
6 1112 Connected
7 111f Connected
8 1132 Connected Message access request
答案 1 :(得分:0)
通常有一组UUID表示不同的操作模式,如文件传输(FTP),远程SIM卡,电话簿请求等。
您可以查询并尝试界面上的所有UUID,如下所示:
device = (from bd in adapter.BondedDevices
where bd.Name == "YourDeviceName"
select bd).FirstOrDefault();
Android.OS.ParcelUuid[] parcel = device.GetUuids();
for (int i = 0; i < parcel.Length; i++) {
socket = device.CreateRfcommSocketToServiceRecord(parcel[i].Uuid);
try {
socket.Connect();
break;
}
catch {
throw new Exception("Unsupported UUID");
}
}
还要确保没有其他设备连接到PC / Android并且打开套接字,因为一次只能为一个插槽提供服务。您可以拥有任意数量的对,但只能运行一个套接字。