title: Intent Service with Bluetooth - Android Studio
body: <p>I'm developing an app which uses Bluetooth connection - so far - to send and receive data from Arduino.
  I was using an Activity and now I'm trying to switch to Fragments, so I can share data between then.
  The problem: the Bluetooth part of the code can't be copied in all fragments, nor stay in the old activity. Which means that I need to find a way to keep the same Bluetooth connection active in whatever fragment open so they can communicate and share data between themselves.
  I was wondering: what is the best approach to that? IntentService Class? Creating a whole interface just for the Bluetooth parameters? </p>
  
  <pre><code>package br.com.fespy.fespybluetooth;
  
  import android.app.Activity;
  import android.bluetooth.BluetoothAdapter;
  import android.bluetooth.BluetoothDevice;
  import android.bluetooth.BluetoothSocket;
  import android.content.Intent;
  import android.os.Bundle;
  import android.support.design.widget.FloatingActionButton;
  import android.support.design.widget.Snackbar;
  import android.support.v7.app.ActionBar;
  import android.view.View;
  import android.support.design.widget.NavigationView;
  import android.support.v4.view.GravityCompat;
  import android.support.v4.widget.DrawerLayout;
  import android.support.v7.app.ActionBarDrawerToggle;
  import android.support.v7.app.AppCompatActivity;
  import android.support.v7.widget.Toolbar;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.widget.CompoundButton;
  import android.widget.Switch;
  import android.widget.Toast;
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.util.UUID;
  
  public class NavDrawer extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
  
      //STATEMENTS DECLARATIONS
  
      Switch switch1, switch2, switch3;
      boolean btState = false;
      boolean test = true;
      private static String MAC = null;
      private static final int REQUEST_ENABLE_BT = 1;
      private static final int REQUEST_CONNECTION_BT = 2;
  
      BluetoothAdapter myBluetoothAdapter = null;
      BluetoothDevice myBluetoothDevice = null;
      BluetoothSocket myBluetoothSocket = null;
  
      UUID myUUID = UUID.fromString("00000003-0000-1000-8000-00805f9b34fb");
  
  
      NavDrawer.ConnectedThread connectedThread;
  
      public void startService (View view)
      {
          Intent intent = new Intent(this, Bluetooth.class);
          startService(intent);
          Toast.makeText(this, "Back up to their brains.",Toast.LENGTH_LONG).show();
      }
  
  
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_nav_drawer);
          Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
          setSupportActionBar(toolbar);
  
          //HOME TITLE
  
          setTitle("");
  
          //DISPLAYS THE FESPY LOGO
          ActionBar actionBar = getSupportActionBar();
          actionBar.setDisplayShowHomeEnabled(true);
          actionBar.setIcon(R.mipmap.fespy2);
  
          DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
          ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                  this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
          drawer.setDrawerListener(toggle);
          toggle.syncState();
          NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
          navigationView.setNavigationItemSelectedListener(this);
  
  
          //SWITCH BUTTONS
          switch1 = (Switch) findViewById(R.id.switch1);
          switch2 = (Switch) findViewById(R.id.switch2);
          switch3 = (Switch) findViewById(R.id.switch3);
  
  
          //LOADS OF BLUETOOTH SETTINGS
  
          myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  
          if (myBluetoothAdapter == null) {
              Toast.makeText(getApplicationContext(), "Device disconnected.", Toast.LENGTH_LONG).show();
          } else if (!myBluetoothAdapter.isEnabled()) //CHECK FOR BLUETOOTH CONNECTION
          {
              Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
              startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
          }
  
  
          switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
              @Override
              public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                  if (isChecked) {
                      if (btState) {
                        connectedThread.write("1");
  
                      } else {
                          Toast.makeText(getApplicationContext(), "Bluetooth is not connected.", Toast.LENGTH_LONG).show();
                          switch1.setChecked(false);
                      }
                  } else {
                      if (btState) {
                          connectedThread.write("0");
                      } else {
                          Toast.makeText(getApplicationContext(), "Bluetooth is not connected.", Toast.LENGTH_LONG).show();
                          switch1.setChecked(false);
                      }
                  }
  
              }
          });
  
          switch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
              @Override
              public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                  if (isChecked) {
                      if (btState) {
                          connectedThread.write("3");
                      } else {
                          Toast.makeText(getApplicationContext(), "Bluetooth is not connected.", Toast.LENGTH_LONG).show();
                          switch2.setChecked(false);
                      }
                  } else {
                      if (btState) {
                          connectedThread.write("2");
                      } else {
                          Toast.makeText(getApplicationContext(), "Bluetooth is not connected.", Toast.LENGTH_LONG).show();
                          switch2.setChecked(false);
                      }
                  }
  
              }
          });
  
          switch3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
              @Override
              public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                  if (isChecked) {
                      if (btState) {
                          connectedThread.write("5");
                      } else {
                          Toast.makeText(getApplicationContext(), "Bluetooth is not connected.", Toast.LENGTH_LONG).show();
                          switch3.setChecked(false);
                      }
                  } else {
                      if (btState) {
                          connectedThread.write("4");
                      } else {
                          Toast.makeText(getApplicationContext(), "Bluetooth is not connected.", Toast.LENGTH_LONG).show();
                          switch3.setChecked(false);
                      }
                  }
  
              }
          });
  
  
      }
  
      @Override
      public void onBackPressed() {
          DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
          if (drawer.isDrawerOpen(GravityCompat.START)) {
              drawer.closeDrawer(GravityCompat.START);
          } else {
              drawer.closeDrawer(GravityCompat.START);
              super.onBackPressed();
          }
      }
  
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.header_menu, menu);
          return true;
      }
  
      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          // Handle action bar item clicks here. The action bar will
          // automatically handle clicks on the Home/Up button, so long
          // as you specify a parent activity in AndroidManifest.xml.
          int id = item.getItemId();
  
          if (id == R.id.action_settings) //SETTINGS FROM NAV BAR
          {
              startActivity(new Intent(this, Settings.class));
          }
  
  
          //BLUETOOTH CONNECTION BUTTON
  
          switch (item.getItemId()) {
              case R.id.btConnect: {
                  if (btState) {
                      try {
                          myBluetoothSocket.close();
                          btState = false;
                          Toast.makeText(getApplicationContext(), "Bluetooth disconnected.", Toast.LENGTH_LONG).show();
  
                      } catch (IOException error) {
                          Toast.makeText(getApplicationContext(), "Error" + error, Toast.LENGTH_LONG).show();
                      }
                  } else {
                      Intent openList = new Intent(NavDrawer.this, AvailableDevices.class);
                      startActivityForResult(openList, REQUEST_CONNECTION_BT);
                  }
              }
  
  
  
          }
  
          return super.onOptionsItemSelected(item);
      }
  
  
      @SuppressWarnings("StatementWithEmptyBody")
      @Override
  
      public boolean onNavigationItemSelected(MenuItem item) {
          int id = item.getItemId();
          android.app.FragmentManager fragmentManager = getFragmentManager();
  
          if (id == R.id.nav_home) {
              fragmentManager.beginTransaction()
                      .replace(R.id.content_frame, new FirstFragment()).commit();
  
          } else if (id == R.id.nav_share) {
  
              fragmentManager.beginTransaction()
                      .replace(R.id.content_frame, new SecondFragment()).commit();
  
          } else if (id == R.id.nav_about) {
              fragmentManager.beginTransaction()
                      .replace(R.id.content_frame, new ThirdFragment()).commit();
          }
  
          if (id == R.id.nav_settings) {
              startActivity(new Intent(this, Settings.class));
          }
  
          DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
          drawer.closeDrawer(GravityCompat.START);
          return true;
  
      }
  
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
  
          switch (requestCode) {
              case REQUEST_ENABLE_BT:
                  if (resultCode == Activity.RESULT_OK) {
                      Toast.makeText(getApplicationContext(), "Bluetooth activated.", Toast.LENGTH_LONG).show();
                  } else {
                      Toast.makeText(getApplicationContext(), "The app needs a bluetooth connection.", Toast.LENGTH_LONG).show();
                      finish();
                  }
                  break;
  
              case REQUEST_CONNECTION_BT:
                  if (resultCode == Activity.RESULT_OK) {
                      MAC = data.getExtras().getString(AvailableDevices.MAC_ADDRESS);
                      myBluetoothDevice = myBluetoothAdapter.getRemoteDevice(MAC);
  
                      try {
                          myBluetoothSocket = myBluetoothDevice.createRfcommSocketToServiceRecord(myUUID);
                          myBluetoothSocket = (BluetoothSocket) myBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(myBluetoothDevice, 1);
                          Toast.makeText(getApplicationContext(), "Connecting...", Toast.LENGTH_LONG).show();
                          myBluetoothSocket.connect();
                          Toast.makeText(getApplicationContext(), "Connected.", Toast.LENGTH_LONG).show();
                          btState = true;
  
                          connectedThread = new NavDrawer.ConnectedThread(myBluetoothSocket);
                          connectedThread.start();
                      } catch (Exception e2) {
                          Toast.makeText(getApplicationContext(), "Error. Try again.", Toast.LENGTH_LONG).show();
                          //connect.setChecked(false); &lt;&lt;removed from the code
                          btState = false;
                      }
                  } else //missclick
                  {
                      Toast.makeText(getApplicationContext(), "Try again.", Toast.LENGTH_LONG).show();
                      //connect.setChecked(false); &lt;&lt;removed from the code
                  }
  
          }
      }
  
      class ConnectedThread extends Thread {
          private final InputStream mmInStream;
          private final OutputStream mmOutStream;
  
          public ConnectedThread(BluetoothSocket socket) {
              InputStream tmpIn = null;
              OutputStream tmpOut = null;
  
              // Get the input and output streams, using temp objects because
              // member streams are final
              try {
                  tmpIn = socket.getInputStream();
                  tmpOut = socket.getOutputStream();
              } catch (IOException e) {
              }
  
              mmInStream = tmpIn;
              mmOutStream = tmpOut;
          }
  
          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 = mmInStream.read(buffer);
                      // Send the obtained bytes to the UI activity
                      // mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                      //   .sendToTarget();
                  } catch (IOException e) {
                      break;
                  }
              }
          }
  
          /* Call this from the main activity to send data to the remote device */
          public void write(String sentData) {
              byte[] msgBuffer = sentData.getBytes();
              try {
                  mmOutStream.write(msgBuffer);
              } catch (IOException e) {
              }
          }
      }
  }
  </code></pre>