ClientThread.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package de.tudarmstadt.informatik.hostage.sync.bluetooth;
  2. import java.io.IOException;
  3. import android.bluetooth.BluetoothDevice;
  4. import android.bluetooth.BluetoothSocket;
  5. import android.os.Handler;
  6. /**
  7. * Thread used to connect to a remote bluetooth device.
  8. * @author Lars Pandikow
  9. */
  10. public class ClientThread extends Thread {
  11. private final BluetoothSocket socket;
  12. private final Handler mHandler;
  13. public ClientThread(BluetoothDevice device, Handler handler) {
  14. mHandler = handler;
  15. BluetoothSocket tmp = null;
  16. try {
  17. tmp = device.createRfcommSocketToServiceRecord(BluetoothSyncActivity.serviceUUID);
  18. } catch (IOException e) {
  19. }
  20. socket = tmp;
  21. }
  22. /** Will cancel an in-progress connection, and close the socket */
  23. public void cancel() {
  24. try {
  25. socket.close();
  26. } catch (IOException e) {
  27. }
  28. }
  29. @Override
  30. public void run() {
  31. try {
  32. socket.connect();
  33. mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_ESTABLISHED, socket).sendToTarget();
  34. } catch (IOException connectException) {
  35. mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_FAILED).sendToTarget();
  36. // Unable to connect; close the socket and get out
  37. try {
  38. socket.close();
  39. } catch (IOException closeException) {
  40. }
  41. return;
  42. }
  43. }
  44. }