BluetoothSyncActivity.java 8.6 KB

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