title: How to keep a Bluetooth connection alive across multiple activities?
body: <p>I cannot find an answer to my specific problem anywhere.</p>
  
  <p>I need a way to have my application activities be able to all separately exchang data with a Bluetooth connection. Here's what I am trying to do:</p>
  
  <p>I have a main activity with a bunch of buttons on it that each start a new activity. One of the buttons is supposed to establish the Bluetooth connection. After it is created, I want to be able to return to the main activity and then hit a different button to open a new activity that can still send and receive data on the Bluetooth connection created earlier.</p>
  
  <p>I'm pretty new at java/android but I'm in desperate need for help because I need to set this app up for a team project I am a part of. Currently I've just been gathering bits of code from around the internet to create an app that simply connects to a specific BT module upon start-up. But this app is kind of worthless if I can't open new pages (activities).</p>
  
  <p>Both the classes for the connectBluetooth and sendReceiveBytes are started as threads. But I believe those threads die when the activity they were started in dies (main activity). So if there is anyway to do this, please enlighten me. Or if you need more information, please let me know and I can help you out. Thanks all!</p>
  
  <p>Here is my code: It is simply a single startup activity that immediately connects to a bt device named "RNBT-504D". And when I leave the application and the activity dies, the connection is closed because of my onDestroy method.</p>
  
  <p>I have shown my broadcast receiver which starts the connect thread and if successful, starts a manage conection thread (sendReceiveBytes). All three classes are shown below.</p>
  
  <pre><code>/* This BroadcastReceiver will display discovered Bluetooth devices */
      public class myOwnBroadcastReceiver extends BroadcastReceiver {
          ConnectToBluetooth connectBT;
  
          @Override
          public void onReceive(Context context, Intent intent) {
              String action=intent.getAction();
  
              //Notification that BluetoothDevice is FOUND
              if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  
  
                  //Gather information about discovered bluetooth device
                  BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  
  
                  //Display more information about the discovered device
                  if(discoveredDevice.getName().equals("RNBT-504D")){
                      ToastMaster("Device: " + discoveredDevice.getName() +"\n"+ discoveredDevice.getAddress());
                  }
  
                  //Connect to the discovered Bluetooth device (SeeedBTSlave)
                  if (discoveredDevice.getName().equals("RNBT-504D")) {
                      ToastMaster("Connecting you Now !!");
                      unregisterReceiver(myDiscoverer);
                      connectBT = new ConnectToBluetooth(discoveredDevice);
                      //Connect to the the device in a new thread
                      new Thread(connectBT).start();
                  }
              }
  
              //Notification if bluetooth device is connected
              if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                  ToastMaster("CONNECTED _ YAY");
  
                  while (scSocket==null) {
                      //do nothing
                  }
                  if (scSocket!=null) {
                      sendReceiveBT = new SendReceiveBytes(scSocket);
                      new Thread(sendReceiveBT).start();
                      //String red = "r";
                      //byte[] myByte = stringToBytesUTFCustom(red);
                      byte[] pronto = new byte[]{0x00, 0x00, 0x00, 0x6E, 0x00, 0x22, 0x00, 0x02, 0x01, 0x56, 0x00, (byte) 0xAC, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x05, (byte) 0x8C, 0x01, 0x56, 0x00, 0x56, 0x00, 0x15, 0x0E, 0x44};
                      sendReceiveBT.write(pronto);
                  }
              }
  
              if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
                  BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                  ToastMaster("Disconnected from "+discoveredDevice.getName());
              }
          }
      }
  
      public static byte[] stringToBytesUTFCustom(String str) {
          char[] buffer = str.toCharArray();
          byte[] b = new byte[buffer.length &lt;&lt; 1];
          for (int i = 0; i &lt; buffer.length; i++) {
              int bpos = i &lt;&lt; 1;
              b[bpos] = (byte) ((buffer[i]&amp;0xFF00)&gt;&gt;8);
              b[bpos + 1] = (byte) (buffer[i]&amp;0x00FF);
          }
          return b;
      }
  
      public class ConnectToBluetooth implements Runnable {
          private BluetoothDevice btShield;
          private BluetoothSocket mySocket = null;
          private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  
          public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
              btShield = bluetoothShield;
              try {
                  mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
              }
              catch(IOException createSocketException) {
                  //Problem with creating a socket
                  Log.e("ConnectToBluetooth", "Error with Socket");
              }
          }
  
          @Override
          public void run() {
              /* Cancel discovery on Bluetooth Adapter to prevent slow connection */
              bluetooth.cancelDiscovery();
  
              try {
                  /*Connect to the bluetoothShield through the Socket. This will block
             until it succeeds or throws an IOException */
                  mySocket.connect();
                  scSocket=mySocket;
              } 
              catch (IOException connectException) {
                  Log.e("ConnectToBluetooth", "Error with Socket Connection");
                  try {
                      mySocket.close(); //try to close the socket
                  }
                  catch(IOException closeException) {
                  }
                  return;
              }
          }
  
          /* Will cancel an in-progress connection, and close the socket */
          public void cancel() {
              try {
                  mySocket.close();
              } 
              catch (IOException e) {
              }
          }
      }
  
  
      private class SendReceiveBytes implements Runnable {
          private BluetoothSocket btSocket;
          private InputStream btInputStream = null;
          private OutputStream btOutputStream = null;
          String TAG = "SendReceiveBytes";
  
          public SendReceiveBytes(BluetoothSocket socket) {
              btSocket = socket;
              try {
                  btInputStream = btSocket.getInputStream();
                  btOutputStream = btSocket.getOutputStream();
              } 
              catch (IOException streamError) { 
                  Log.e(TAG, "Error when getting input or output Stream");
              }
          }
  
  
          public void run() {
              byte[] buffer = new byte[1024]; // buffer store for the stream
              int bytes; // bytes returned from read()
  
              // Keep listening to the InputStream until an exception occurs
              while (true) {
                  try {
                      // Read from the InputStream
                      bytes = btInputStream.read(buffer);
                      // Send the obtained bytes to the UI activity
                      mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                  } 
                  catch (IOException e) {
                      Log.e(TAG, "Error reading from btInputStream");
                      break;
                  }
              }
          }
  
  
          /* Call this from the main activity to send data to the remote device */
          public void write(byte[] bytes) {
              try {
                  btOutputStream.write(bytes);
              } 
              catch (IOException e) { 
                  Log.e(TAG, "Error when writing to btOutputStream");
              }
          }
  
  
          /* Call this from the main activity to shutdown the connection */
          public void cancel() {
              try {
                  btSocket.close();
              } 
              catch (IOException e) { 
                  Log.e(TAG, "Error when closing the btSocket");
              }
          }
      }
  </code></pre>