ServerThread.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. public class ServerThread extends Thread {
  8. private final BluetoothServerSocket serverSocket;
  9. private final Handler mHandler;
  10. public ServerThread(Handler handler, String app_name) {
  11. BluetoothServerSocket tmp = null;
  12. mHandler = handler;
  13. try {
  14. tmp = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(app_name, BluetoothSync.serviceUUID);
  15. } catch (IOException e) {
  16. mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
  17. }
  18. serverSocket = tmp;
  19. }
  20. /** Will cancel the listening socket, and cause the thread to finish */
  21. public void cancel() {
  22. try {
  23. serverSocket.close();
  24. } catch (IOException e) {
  25. }
  26. }
  27. @Override
  28. public void run() {
  29. BluetoothSocket socket = null;
  30. while (true) {
  31. try {
  32. socket = serverSocket.accept();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
  36. break;
  37. }
  38. if (socket != null) {
  39. // Do work to manage the connection (in a separate thread)
  40. mHandler.obtainMessage(BluetoothSync.CONNECTION_ESTABLISHED, socket).sendToTarget();
  41. try {
  42. serverSocket.close();
  43. } catch (IOException e) {
  44. e.printStackTrace();
  45. }
  46. break;
  47. }
  48. }
  49. }
  50. }