BluetoothSyncActivity.java 9.2 KB

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