ClientThread.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. public class ClientThread extends Thread {
  7. private final BluetoothSocket socket;
  8. private final Handler mHandler;
  9. public ClientThread(BluetoothDevice device, Handler handler) {
  10. mHandler = handler;
  11. BluetoothSocket tmp = null;
  12. try {
  13. tmp = device.createRfcommSocketToServiceRecord(BluetoothSync.serviceUUID);
  14. } catch (IOException e) {
  15. }
  16. socket = tmp;
  17. }
  18. /** Will cancel an in-progress connection, and close the socket */
  19. public void cancel() {
  20. try {
  21. socket.close();
  22. } catch (IOException e) {
  23. }
  24. }
  25. @Override
  26. public void run() {
  27. try {
  28. socket.connect();
  29. mHandler.obtainMessage(BluetoothSync.CONNECTION_ESTABLISHED, socket).sendToTarget();
  30. } catch (IOException connectException) {
  31. mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
  32. // Unable to connect; close the socket and get out
  33. try {
  34. socket.close();
  35. } catch (IOException closeException) {
  36. }
  37. return;
  38. }
  39. }
  40. }