ServerThread.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package de.tudarmstadt.informatik.hostage.sync.bluetooth;
  2. import java.io.IOException;
  3. import android.bluetooth.BluetoothAdapter;
  4. import android.bluetooth.BluetoothServerSocket;
  5. import android.bluetooth.BluetoothSocket;
  6. import android.os.Handler;
  7. /**
  8. * Thread listens for incomming connections.
  9. * @author Lars Pandikow
  10. */
  11. public class ServerThread extends Thread {
  12. private final BluetoothServerSocket serverSocket;
  13. private final Handler mHandler;
  14. public ServerThread(Handler handler, String app_name) {
  15. BluetoothServerSocket tmp = null;
  16. mHandler = handler;
  17. try {
  18. tmp = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(app_name, BluetoothSyncActivity.serviceUUID);
  19. } catch (IOException e) {
  20. mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_FAILED).sendToTarget();
  21. }
  22. serverSocket = tmp;
  23. }
  24. /** Will cancel the listening socket, and cause the thread to finish */
  25. public void cancel() {
  26. try {
  27. serverSocket.close();
  28. } catch (IOException e) {
  29. }
  30. }
  31. @Override
  32. public void run() {
  33. BluetoothSocket socket = null;
  34. while (true) {
  35. try {
  36. socket = serverSocket.accept();
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_FAILED).sendToTarget();
  40. break;
  41. }
  42. if (socket != null) {
  43. // Do work to manage the connection (in a separate thread)
  44. mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_ESTABLISHED, socket).sendToTarget();
  45. try {
  46. serverSocket.close();
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. }
  50. break;
  51. }
  52. }
  53. }
  54. }