BluetoothSync.java 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package de.tudarmstadt.informatik.hostage.sync;
  2. import java.io.IOException;
  3. import java.io.ObjectInputStream;
  4. import java.io.ObjectOutputStream;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.UUID;
  8. import android.app.AlertDialog;
  9. import android.bluetooth.BluetoothAdapter;
  10. import android.bluetooth.BluetoothDevice;
  11. import android.bluetooth.BluetoothServerSocket;
  12. import android.bluetooth.BluetoothSocket;
  13. import android.content.BroadcastReceiver;
  14. import android.content.Context;
  15. import android.content.DialogInterface;
  16. import android.content.Intent;
  17. import android.content.IntentFilter;
  18. import android.widget.ArrayAdapter;
  19. import de.tudarmstadt.informatik.hostage.R;
  20. import de.tudarmstadt.informatik.hostage.logging.UglyDbHelper;
  21. public class BluetoothSync {
  22. private class ClientThread extends Thread {
  23. private final BluetoothSocket socket;
  24. public ClientThread(BluetoothDevice device) {
  25. BluetoothSocket tmp = null;
  26. try {
  27. tmp = device.createRfcommSocketToServiceRecord(serviceUUID);
  28. } catch (IOException e) {
  29. }
  30. socket = tmp;
  31. }
  32. /** Will cancel an in-progress connection, and close the socket */
  33. public void cancel() {
  34. try {
  35. socket.close();
  36. } catch (IOException e) {
  37. }
  38. }
  39. @Override
  40. public void run() {
  41. try {
  42. socket.connect();
  43. } catch (IOException connectException) {
  44. // Unable to connect; close the socket and get out
  45. try {
  46. socket.close();
  47. } catch (IOException closeException) {
  48. }
  49. return;
  50. }
  51. manageConnectedSocket(socket, CLIENT);
  52. }
  53. }
  54. private class CommunicationThread extends Thread {
  55. private final BluetoothSocket mmSocket;
  56. private final ObjectInputStream objectInput;
  57. private final ObjectOutputStream objectOuput;
  58. private final int identifier;
  59. public CommunicationThread(BluetoothSocket socket, int identifier) {
  60. mmSocket = socket;
  61. ObjectInputStream tmpIn = null;
  62. ObjectOutputStream tmpOut = null;
  63. // Get the input and output streams, using temp objects because
  64. // member streams are final
  65. try {
  66. tmpOut = new ObjectOutputStream(socket.getOutputStream());
  67. tmpIn = new ObjectInputStream(socket.getInputStream());
  68. } catch (IOException e) {
  69. e.printStackTrace();
  70. }
  71. objectInput = tmpIn;
  72. objectOuput = tmpOut;
  73. this.identifier = identifier;
  74. }
  75. /* Call this from the main activity to shutdown the connection */
  76. public void cancel() {
  77. try {
  78. mmSocket.close();
  79. } catch (IOException e) {
  80. }
  81. }
  82. @Override
  83. public void run() {
  84. // Keep listening to the InputStream until an exception occurs
  85. // while (true) {
  86. try {
  87. // TODO Ersetze dbh mit Logger
  88. UglyDbHelper dbh = new UglyDbHelper(context);
  89. ArrayList<HashMap<String, Object>> localNetworkInformation = dbh
  90. .getNetworkInformation();
  91. if (identifier == SERVER) {
  92. // Read from the InputStream
  93. ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput
  94. .readObject();
  95. ;
  96. dbh.updateNetworkInformation(remoteNetworkInformation);
  97. objectOuput.writeObject(localNetworkInformation);
  98. } else {
  99. objectOuput.writeObject(localNetworkInformation);
  100. // Read from the InputStream
  101. ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput
  102. .readObject();
  103. dbh.updateNetworkInformation(remoteNetworkInformation);
  104. mmSocket.close();
  105. }
  106. } catch (ClassNotFoundException e) {
  107. e.printStackTrace();
  108. } catch (IOException e) {
  109. e.printStackTrace();
  110. }
  111. // }
  112. }
  113. /* Call this from the main activity to send data to the remote device */
  114. public void write(ArrayList<HashMap<String, Object>> networkInformation) {
  115. try {
  116. objectOuput.writeObject(networkInformation);
  117. } catch (IOException e) {
  118. e.printStackTrace();
  119. }
  120. }
  121. }
  122. private class ServerThread extends Thread {
  123. private final BluetoothServerSocket serverSocket;
  124. public ServerThread() {
  125. BluetoothServerSocket tmp = null;
  126. try {
  127. tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
  128. context.getResources().getString(R.string.app_name),
  129. serviceUUID);
  130. } catch (IOException e) {
  131. }
  132. serverSocket = tmp;
  133. }
  134. /** Will cancel the listening socket, and cause the thread to finish */
  135. public void cancel() {
  136. try {
  137. serverSocket.close();
  138. } catch (IOException e) {
  139. }
  140. }
  141. @Override
  142. public void run() {
  143. BluetoothSocket socket = null;
  144. while (true) {
  145. try {
  146. socket = serverSocket.accept();
  147. } catch (IOException e) {
  148. e.printStackTrace();
  149. break;
  150. }
  151. if (socket != null) {
  152. // Do work to manage the connection (in a separate thread)
  153. manageConnectedSocket(socket, SERVER);
  154. try {
  155. serverSocket.close();
  156. } catch (IOException e) {
  157. e.printStackTrace();
  158. }
  159. break;
  160. }
  161. }
  162. }
  163. }
  164. private final UUID serviceUUID;
  165. private final int SERVER = 0;
  166. private final int CLIENT = 1;
  167. private BluetoothAdapter mBluetoothAdapter;
  168. private Context context;
  169. private ArrayAdapter<String> arrayAdapter;
  170. private ServerThread serverThread;
  171. private AlertDialog ad;
  172. // Create a BroadcastReceiver for ACTION_FOUND
  173. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  174. @Override
  175. public void onReceive(Context context, Intent intent) {
  176. String action = intent.getAction();
  177. // When discovery finds a device
  178. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  179. // Get the BluetoothDevice object from the Intent
  180. BluetoothDevice device = intent
  181. .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  182. // Add the name and address to an array adapter to show in a
  183. // ListView
  184. arrayAdapter.add(device.getName() + "\n" + device.getAddress());
  185. arrayAdapter.notifyDataSetChanged();
  186. }
  187. }
  188. };
  189. public BluetoothSync(Context context) {
  190. this.context = context;
  191. serviceUUID = UUID.fromString(context.getResources().getString(
  192. R.string.UUID));
  193. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  194. }
  195. public boolean syncData() {
  196. if (!bluetoothAvaible())
  197. return false;
  198. syncDataPassive();
  199. return syncDataActive();
  200. }
  201. private boolean bluetoothAvaible() {
  202. if (mBluetoothAdapter == null) {
  203. // Device does not support Bluetooth
  204. return false;
  205. }
  206. if (!mBluetoothAdapter.isEnabled()) {
  207. Intent enableBtIntent = new Intent(
  208. BluetoothAdapter.ACTION_REQUEST_ENABLE);
  209. context.startActivity(enableBtIntent);
  210. return false;
  211. }
  212. return true;
  213. }
  214. private void deviceDialog() {
  215. AlertDialog.Builder builder = new AlertDialog.Builder(context);
  216. // TODO in resources auslagern
  217. builder.setTitle("Choose Device");
  218. builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
  219. @Override
  220. public void onClick(DialogInterface dialog, int position) {
  221. String deviceInfo = arrayAdapter.getItem(position);
  222. String mac = deviceInfo.substring(deviceInfo.indexOf("\n") + 1);
  223. ClientThread clientThread = new ClientThread(mBluetoothAdapter
  224. .getRemoteDevice(mac));
  225. clientThread.start();
  226. }
  227. });
  228. // builder.create();
  229. ad = builder.show();
  230. }
  231. private void manageConnectedSocket(BluetoothSocket socket, int identifier) {
  232. if (identifier == SERVER) {
  233. ad.dismiss();
  234. }
  235. mBluetoothAdapter.cancelDiscovery();
  236. context.unregisterReceiver(mReceiver);
  237. CommunicationThread commThread = new CommunicationThread(socket,
  238. identifier);
  239. commThread.start();
  240. }
  241. // Register the BroadcastReceiver
  242. private void registerBroadcastReceiver() {
  243. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  244. context.registerReceiver(mReceiver, filter); // Don't forget to
  245. // unregister during
  246. // onDestroy
  247. }
  248. private boolean syncDataActive() {
  249. registerBroadcastReceiver();
  250. arrayAdapter = new ArrayAdapter<String>(context,
  251. android.R.layout.simple_list_item_1);
  252. // Start scanning for devices
  253. if (!mBluetoothAdapter.startDiscovery())
  254. return false;
  255. deviceDialog();
  256. return true;
  257. }
  258. private void syncDataPassive() {
  259. Intent discoverableIntent = new Intent(
  260. BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  261. discoverableIntent.putExtra(
  262. BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
  263. context.startActivity(discoverableIntent);
  264. serverThread = new ServerThread();
  265. serverThread.start();
  266. }
  267. }