我执行以下操作以连接已配对的设备:
if (connectCreateRfcommSocketToServiceRecordInvoke()) {
Log.d(TAG_BT, "Connection created 1");
connected = true;
} else if (connectCreateRfcommSocket()) {
Log.d(TAG_BT, "Connection created 2");
connected = true;
} else if (connectSecureRfCom(UUID_DEFAULT)) {
Log.d(TAG_BT, "Connection created 3");
connected = true;
} else if (connectInsecureRfCom(UUID_DEFAULT)) {
Log.d(TAG_BT, "Connection created 4");
connected = true;
}else if (tryConnectDifferentUuid()) {
Log.d(TAG_BT, "Connection created 5");
connected = true;
}
以下是被调用函数的定义:
private boolean tryConnectDifferentUuid() {
ParcelUuid[] supportedUuids = mDevice.getUuids();
if (supportedUuids != null){
for (ParcelUuid Uuid : supportedUuids) {
if (connectSecureRfCom(Uuid.toString())) {
return true;
} else if (connectInsecureRfCom(Uuid.toString())) {
return true;
}
}
}
return false;
}
private boolean connectSecureRfCom(String UuidString) {
try {
Log.d(TAG_BT, "connectSecureRfCom ");
mmSocket = mDevice.createRfcommSocketToServiceRecord(UUID.fromString(UuidString));
mmSocket.connect();
Log.d(TAG_BT, "Connected");
return true;
} catch (Exception e) {
Log.e(TAG_BT, "Couldn't establish Bluetooth connection!", e);
return false;
}
}
private boolean connectInsecureRfCom(String UuidString) {
try {
Log.d(TAG_BT, "connectInsecureRfCom ");
mmSocket = mDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString(UuidString));
mmSocket.connect();
Log.d(TAG_BT, "Connected");
return true;
} catch (Exception e) {
Log.e(TAG_BT, "Couldn't establish Bluetooth connection!", e);
return false;
}
}
private boolean connectCreateRfcommSocket() {
try {
Log.d(TAG_BT, "connectSecureRfComInvoke ");
mmSocket =(BluetoothSocket) mDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mDevice,1);
mmSocket.connect();
Log.d(TAG_BT, "Connected");
return true;
} catch (Throwable e) {
Log.e(TAG_BT, "Couldn't establish Bluetooth connection!", e);
return false;
}
}
private boolean connectCreateRfcommSocketToServiceRecordInvoke() {
try {
Log.d(TAG_BT, "createRfcommSocketToServiceRecord ");
mmSocket =(BluetoothSocket) mDevice.getClass().getMethod("createRfcommSocketToServiceRecord", new Class[] {int.class}).invoke(mDevice,1);
mmSocket.connect();
Log.d(TAG_BT, "Connected");
return true;
} catch (Throwable e) {
Log.e(TAG_BT, "Couldn't establish Bluetooth connection!", e);
return false;
}
}
问题是它有时连续多次工作,无论我打开/关闭应用程序还是断开/连接蓝牙,有时它不能使用以下输出:
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
答案 0 :(得分:1)
好吧,如果没有找到读或写,插座会在一段时间后关闭或超时。您应该在具有无限循环的不同线程中使用套接字。
public class Client extends(Thread or AsyncTask or Runnable ){
public void startConnection(){socket.connect(); isConnected = socket.isConnected();}
private void listenSocket(){
while(isConnected){ listening process }}
public void stopConnection(){thread.cancel(); isConnected = false;}
}