BluetoothSyncActivity.java 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. package de.tudarmstadt.informatik.hostage.sync.bluetooth;
  2. import java.util.UUID;
  3. import android.app.Activity;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.bluetooth.BluetoothSocket;
  7. import android.content.BroadcastReceiver;
  8. import android.content.Context;
  9. import android.content.Intent;
  10. import android.content.IntentFilter;
  11. import android.os.Bundle;
  12. import android.os.Handler;
  13. import android.os.Message;
  14. import android.view.View;
  15. import android.widget.AdapterView;
  16. import android.widget.ArrayAdapter;
  17. import android.widget.ListView;
  18. import android.widget.TextView;
  19. import android.widget.AdapterView.OnItemClickListener;
  20. import de.tudarmstadt.informatik.hostage.R;
  21. import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
  22. import de.tudarmstadt.informatik.hostage.sync.Synchronizer;
  23. /**
  24. * Activity that allows the user to choose a bluetooth device to
  25. * synchronize with and informs about the status of the synchronization.
  26. *
  27. * @author Lars Pandikow
  28. */
  29. public class BluetoothSyncActivity extends Activity{
  30. public static final int CONNECTING = 0x0;
  31. public static final int CONNECTION_ESTABLISHED = 0x1;
  32. public static final int CONNECTION_FAILED = 0x2;
  33. public static final int SYNC_SUCCESSFUL = 0x3;
  34. public static final int SYNC_FAILED = 0x4;
  35. public static UUID serviceUUID;
  36. private BluetoothAdapter mBluetoothAdapter;
  37. private ArrayAdapter<String> arrayAdapter;
  38. private ServerThread serverThread;
  39. private ClientThread clientThread;
  40. private CommunicationThread commThread;
  41. private TextView mInfoText;
  42. private ListView listView;
  43. private HostageDBOpenHelper mDbHelper;
  44. private Synchronizer synchronizer;
  45. @Override
  46. public void onCreate(Bundle savedInstanceState){
  47. super.onCreate(savedInstanceState);
  48. setContentView(R.layout.activity_bluetooth);
  49. mDbHelper = new HostageDBOpenHelper(getApplicationContext());
  50. synchronizer = new Synchronizer(mDbHelper);
  51. serviceUUID = UUID.fromString(getResources().getString(R.string.UUID));
  52. mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  53. arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_view_bluetooth_devices);
  54. setLayoutElement();
  55. registerBroadcastReceiver();
  56. if(savedInstanceState != null){
  57. CharSequence text = savedInstanceState.getCharSequence("mInfoText");
  58. mInfoText.setText(text);
  59. String[] data = savedInstanceState.getStringArray("adapter");
  60. if(data != null){
  61. for(int i = 0; i < data.length; i++){
  62. arrayAdapter.add(data[i]);
  63. arrayAdapter.notifyDataSetChanged();
  64. }
  65. }
  66. if(savedInstanceState.getBoolean("listView")){
  67. listView.setVisibility(View.VISIBLE);
  68. }else{
  69. listView.setVisibility(View.GONE);
  70. }
  71. }
  72. if (mBluetoothAdapter == null) {
  73. // Device does not support Bluetooth
  74. mInfoText.setText("Bluetooth is not available on this device.");
  75. }
  76. else if (!mBluetoothAdapter.isEnabled()) {
  77. mInfoText.setText("Enable Bluetooth before synchronizing.");
  78. Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  79. startActivity(enableBtIntent);
  80. } else if(savedInstanceState == null){
  81. startConnectionListener();
  82. chooseDevice();
  83. }
  84. }
  85. @Override
  86. public void onDestroy(){
  87. super.onDestroy();
  88. if(mRecieverRegistered){
  89. unregisterBroadcastReceiver();
  90. }
  91. cancelThreads();
  92. }
  93. @Override
  94. protected void onSaveInstanceState(Bundle outState){
  95. String[] data = new String[arrayAdapter.getCount()];
  96. for(int i = 0; i < arrayAdapter.getCount(); i++){
  97. data[i] = arrayAdapter.getItem(i);
  98. }
  99. outState.putStringArray("adapter", data);
  100. outState.putCharSequence("mInfoText", mInfoText.getText());
  101. outState.putBoolean("listView", listView.isShown());
  102. super.onSaveInstanceState(outState);
  103. }
  104. /**
  105. * Starts discovery of bluetooth devices.
  106. */
  107. private void chooseDevice(){
  108. if (!mBluetoothAdapter.startDiscovery())
  109. return;
  110. mInfoText.setText("Choose Device for synchronizing:\n");
  111. listView.setVisibility(View.VISIBLE);
  112. }
  113. /**
  114. * Start a ServerThread to listen for incoming connections
  115. * @see ServerThread
  116. */
  117. private void startConnectionListener() {
  118. if(mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
  119. Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  120. discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
  121. startActivity(discoverableIntent);
  122. }
  123. serverThread = new ServerThread(mHandler, getResources().getString(R.string.app_name));
  124. serverThread.start();
  125. }
  126. /**
  127. * Called when a connection has been established.
  128. * Starts a {@link CommunicationThread} for communication.
  129. * @param socket The socket of the connection.
  130. */
  131. protected void manageConnectedSocket(BluetoothSocket socket) {
  132. mBluetoothAdapter.cancelDiscovery();
  133. unregisterBroadcastReceiver();
  134. listView.setVisibility(View.GONE);
  135. String deviceName = socket.getRemoteDevice().getName();
  136. mInfoText.setText("Synchronizing with " + deviceName + "...");
  137. commThread = new CommunicationThread(this, socket, mHandler);
  138. commThread.start();
  139. }
  140. /**
  141. * BroadcastReciever listens for state changes of bluetooth and discovery of new devices.
  142. */
  143. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  144. @Override
  145. public void onReceive(Context context, Intent intent) {
  146. String action = intent.getAction();
  147. // When discovery finds a device
  148. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  149. // Get the BluetoothDevice object from the Intent
  150. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  151. // Add the name and address to an array adapter to show in a ListView
  152. arrayAdapter.add(device.getName() + "\n" + device.getAddress());
  153. arrayAdapter.notifyDataSetChanged();
  154. }else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
  155. int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
  156. if(state == BluetoothAdapter.STATE_ON){
  157. startConnectionListener();
  158. chooseDevice();
  159. }else if(state == BluetoothAdapter.STATE_OFF || state == BluetoothAdapter.STATE_TURNING_OFF){
  160. mInfoText.setText("Enable Bluetooth before synchronizing.");
  161. listView.setVisibility(View.GONE);
  162. }
  163. }
  164. }
  165. };
  166. private boolean mRecieverRegistered = false;
  167. /**
  168. * Register the BroadcastReceiver
  169. */
  170. private void registerBroadcastReceiver() {
  171. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  172. filter.addAction(BluetoothAdapter. ACTION_STATE_CHANGED);
  173. registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
  174. mRecieverRegistered = true;
  175. }
  176. /**
  177. * Unregister the BroadcastReceiver
  178. */
  179. private void unregisterBroadcastReceiver(){
  180. unregisterReceiver(mReceiver);
  181. mRecieverRegistered = false;
  182. }
  183. /**
  184. * Creates the list of bluetooth devices.
  185. * Starts a {@link ClientThread} to establish connection when a device is clicked.
  186. */
  187. private void setLayoutElement(){
  188. mInfoText = (TextView) findViewById(R.id.bluetoothInfoText);
  189. listView = (ListView) findViewById(R.id.bluetoothListView);
  190. listView.setAdapter(arrayAdapter);
  191. listView.setOnItemClickListener(new OnItemClickListener() {
  192. @Override
  193. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  194. String deviceInfo = arrayAdapter.getItem(position);
  195. String mac = deviceInfo.substring(deviceInfo.indexOf("\n") + 1);
  196. String name = deviceInfo.substring(0, deviceInfo.indexOf("\n"));
  197. mHandler.obtainMessage(CONNECTING, name).sendToTarget();
  198. clientThread = new ClientThread(mBluetoothAdapter.getRemoteDevice(mac), mHandler);
  199. clientThread.start();
  200. }
  201. });
  202. }
  203. private void cancelThreads(){
  204. if(commThread != null) {
  205. commThread.cancel();
  206. }
  207. if(clientThread != null){
  208. clientThread.cancel();
  209. }
  210. if(serverThread != null){
  211. serverThread.cancel();
  212. }
  213. }
  214. /**
  215. * Handles message sent from the background threads and updates UI.
  216. */
  217. private Handler mHandler = new Handler() {
  218. @Override
  219. public void handleMessage(Message msg) {
  220. switch(msg.what){
  221. case CONNECTING:
  222. listView.setVisibility(View.GONE);
  223. mInfoText.setText("Connecting to " + (String)msg.obj + "!");
  224. break;
  225. case CONNECTION_ESTABLISHED:
  226. BluetoothSocket socket = (BluetoothSocket) msg.obj;
  227. manageConnectedSocket(socket);
  228. break;
  229. case CONNECTION_FAILED:
  230. mInfoText.setText("Failed to connect to device!");
  231. break;
  232. case SYNC_SUCCESSFUL:
  233. mInfoText.setText("Synchronization successfull!");
  234. break;
  235. case SYNC_FAILED:
  236. commThread.cancel();
  237. mInfoText.setText("Synchronization failed!");
  238. break;
  239. }
  240. }
  241. };
  242. }