1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| private class ConnectThread extends Thread {
private final BluetoothDevice mmDevice;
@SuppressLint("NewApi")
public ConnectThread(BluetoothDevice device) {
Log.v("ConnectionHelper", "ConnectThread");
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
// Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
// tmp = (BluetoothSocket) m.invoke(device, 1);
tmp = device.createRfcommSocketToServiceRecord(SERVER_UUID);
// tmp =
// device.createInsecureRfcommSocketToServiceRecord(SERVER_UUID);
}catch (IOException e) {
Log.e(TAG, "create() failed", e);
} /*catch (SecurityException e) {
Log.e("createRfcommSocket", "SecurityException " + e.getMessage());
} catch (NoSuchMethodException e) {
Log.e("createRfcommSocket", "NoSuchMethodException " + e.getMessage());
} catch (IllegalArgumentException e) {
Log.e("createRfcommSocket", "IllegalArgumentException " + e.getMessage());
} catch (IllegalAccessException e) {
Log.e("createRfcommSocket", "IllegalAccessException " + e.getMessage());
} catch (InvocationTargetException e) {
Log.e("createRfcommSocket", "InvocationTargetException " + e.getMessage());
}*/
ConnectionHelper.this.clientSocket = tmp;
}
@Override
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
ConnectionHelper.this.clientSocket.connect();
ConnectionHelper.this.outputStream = ConnectionHelper.this.clientSocket
.getOutputStream();
ConnectionHelper.this.inputStream = ConnectionHelper.this.clientSocket
.getInputStream();
ConnectionHelper.this.buffInputStream = new BufferedReader(new InputStreamReader(inputStream));
} catch (IOException e) {
connectionFailed(e);
ConnectionHelper.this.closeConnection();
// Start the service over to restart listening mode
ConnectionHelper.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (ConnectionHelper.this) {
mConnectThread = null;
}
// Start the connected thread
connected(clientSocket, mmDevice);
}
public void cancel() {
ConnectionHelper.this.closeConnection();
}
} |
Partager