title: Arduino Android Bluetooth Serial Communication
body: <p>I have an Arduino Bluetooth shield HC-05. I paired the Bluetooth shield first with Android device and tried to send data to Arduino via Bluetooth shield. Android app sends data to the shield. But Arduino not receiving the command more than (4 to 13) times I think my app not holding the connection properly with the Bluetooth shield, I am not sure about the problem. I tried with the same Arduino code with some other Android application. It was working well. So problem is in my code only. I am using log to monitor the flow of code. The data is sending from the Android device and the Bluetooth is live and still paired. I think Bluetooth shield was not receiving or it was receiving and not passing the data to Arduino. I am troubling for couple of weeks.</p>
  
  <p>Thanks in Advance !!</p>
  
  <p>My code goes here...</p>
  
  <pre><code>private BluetoothAdapter mBluetoothAdapter = null;
  private BluetoothSocket btSocket = null;
  private OutputStream outStream = null;
  private static String address = "98:D3:31:30:25:DC";//old: 20:14:12:03:12:42, 98:D3:31:30:25:DC
  private static final UUID MY_UUID = UUID
          .fromString("00001101-0000-1000-8000-00805F9B34FB");
  private InputStream inStream = null;
  Handler handler = new Handler(); 
  byte delimiter = 10;
  boolean stopWorker = false;
  int readBufferPosition = 0;
  byte[] readBuffer = new byte[1024];
  //
  //Bluetooth sender ends
  //
  //
  
   private final  BroadcastReceiver commandAction = new BroadcastReceiver() {
                  @Override
                  public void onReceive(Context context2, Intent intent2) {
                      String com = intent2.getStringExtra("key");
                      commandAction(com); 
                      Toast.makeText(context2, "commandAction:"+com, Toast.LENGTH_SHORT).show();
                  }
             };
  
  
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  
      setContentView(R.layout.activity_main);
      final Button button = (Button) findViewById(R.id.button);
      button.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              commandAction("up");
          }
      });
      GCMRegistrar.checkDevice( this );
      GCMRegistrar.checkManifest( this );
      final String regId = GCMRegistrar.getRegistrationId( this );
      if( regId.equals( "" ) ) {
          GCMRegistrar.register( this, "501396392354" );
          Toast.makeText(this," 501396392354", Toast.LENGTH_SHORT).show();
      }
      else {
          Toast.makeText(this,regId, Toast.LENGTH_SHORT).show();
          Log.v( TAG2, "Already registered" );
          Log.v(TAG2, "Registration id is: " + regId );
      }
  
  
  
      startService(new Intent(MainActivity.this, LocationService.class)); 
  
      CheckBt();
      Connect();
      BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
      Log.e("Jon", device.toString());
  
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.activity_main, menu);
      return true;
  }
  
  
  @Override
  public Object onRetainNonConfigurationInstance() {
      if (mAccessory != null) {
          return mAccessory;
      } else {
          return super.onRetainNonConfigurationInstance();
      }
  }
  
  @Override
  public void onResume() {
      super.onResume();
  
      IntentFilter intentFilter = new IntentFilter();
      intentFilter.addAction("in.robot.gcm.commandaction");
      registerReceiver(commandAction, intentFilter);
  
      if (mInputStream != null &amp;&amp; mOutputStream != null) {
          return;
      }
  }
  
  @Override
  public void onPause() {
      super.onPause();
       unregisterReceiver(commandAction);
      closeAccessory();
  }
  
  @Override
  public void onDestroy() {
      unregisterReceiver(mUsbReceiver);
  
      stopService(new Intent(MainActivity.this, LocationService.class));
  
  
      try {
          btSocket.close();
      } catch (IOException e) {
      }
      super.onDestroy();
  }
  
  private void openAccessory(UsbAccessory accessory) {
      mFileDescriptor = mUsbManager.openAccessory(accessory);
      if (mFileDescriptor != null) {
          mAccessory = accessory;
          FileDescriptor fd = mFileDescriptor.getFileDescriptor();
          mInputStream = new FileInputStream(fd);
          mOutputStream = new FileOutputStream(fd);
          Log.d(TAG, "accessory opened");
      } else {
          Log.d(TAG, "accessory open fail");
      }
  }
  
  
  private void closeAccessory() {
      try {
          if (mFileDescriptor != null) {
              mFileDescriptor.close();
          }
      } catch (IOException e) {
      } finally {
          mFileDescriptor = null;
          mAccessory = null;
      }
  }
  
  public void commandAction(String command){
  
      byte[] buffer = new byte[1];
      MediaPlayer mp;
  
      Toast.makeText(this,"in cmd action",Toast.LENGTH_SHORT).show();
  
      if("up".equals(command)){
          buffer[0]=(byte)0;
          Log.v(TAG ,"up heay");
          writeData("1");
          Toast.makeText(this,"UP",Toast.LENGTH_SHORT).show();
      }
  
      else if("down".equals(command)) {
          buffer[0]=(byte)1;
          Log.v(TAG ,"down heay");
          writeData("2");
      }
  
      else if("left".equals(command)){
          buffer[0]=(byte)2;
          writeData("3");
      }
      else if("right".equals(command)){
          buffer[0]=(byte)3;
          writeData("4");
      }
      else if("break".equals(command)){
          buffer[0]=(byte)4;
          writeData("0");
      }
  
      else if("camera left".equals(command)){
          buffer[0]=(byte)5;
          //writeData("0");
      }
      else if("camera right".equals(command)){
          buffer[0]=(byte)6;
          //writeData("0");
      }
  
      else if ("jigsaw1".equals(command)){
           mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw1);  
            mp.start();
            }
  
          else if("jigsaw2".equals(command)){
               mp = MediaPlayer.create(MainActivity.this, R.raw.jigsaw2);  
                mp.start();
          }
          else if("horn".equals(command)){
               mp = MediaPlayer.create(MainActivity.this, R.raw.horn);  
                mp.start();
          }
          else if("start".equals(command)){
               mp = MediaPlayer.create(MainActivity.this, R.raw.start);  
                mp.start();
          }
          else if("ghosts".equals(command)){
               mp = MediaPlayer.create(MainActivity.this, R.raw.ghosts);  
                mp.start();
          }
          else if("flash on".equals(command)){
  
              if((this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) &amp;&amp; !(isLighOn)){
  
                   cam = Camera.open();     
                      Parameters params = cam.getParameters();
                      params.setFlashMode(Parameters.FLASH_MODE_ON);
                      cam.setParameters(params);
                      cam.startPreview();
                      isLighOn=true; 
                      Log.v("camera","flash on");
              }
              else{Log.v("camera","flash not exsisted");}
  
          }
  
          else if("flash off".equals(command)){
              if(isLighOn){
              cam.stopPreview();
               cam.release();
               isLighOn=false;
               Log.v("camera","flash off");   
          } }
  
          else if("location on".equals(command)){
                startService(new Intent(MainActivity.this, LocationService.class)); 
          }
          else if("location off".equals(command)){
              stopService(new Intent(MainActivity.this, LocationService.class));
          }
  
          else if("speed min".equals(command)){
              buffer[0]=(byte)7;
          }
  
          else if("speed min".equals(command)){
              buffer[0]=(byte)8;
          }
          else if("speed max".equals(command)){
              buffer[0]=(byte)9;
          }
  
      else{
          Log.v(TAG ,"no command recieved");}
  
  
  
      if (mOutputStream != null) {
          try {
              mOutputStream.write(buffer);
          } catch (IOException e) {
              Log.e(TAG, "write failed", e);
          }
      }
  }
  
  
  //
  //
  //
  //
  private void CheckBt() {
      mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  
      if (!mBluetoothAdapter.isEnabled()) {
          Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
                  Toast.LENGTH_SHORT).show();
      }
  
      if (mBluetoothAdapter == null) {
          Toast.makeText(getApplicationContext(),
                  "Bluetooth null !", Toast.LENGTH_SHORT)
                  .show();
      }
  }
  
      public void Connect() {
          Log.d(TAG, address);
          BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
          Log.d(TAG, "Connecting to ... " + device);
          Toast.makeText(this, "Connecting to...", Toast.LENGTH_SHORT).show();
          mBluetoothAdapter.cancelDiscovery();
          try {
              btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
              btSocket.connect();
              Log.d(TAG, "Connection made.");
              Toast.makeText(this, "Connection made Successful..", Toast.LENGTH_SHORT).show();
          } catch (IOException e) {
              try {
                  btSocket.close();
              } catch (IOException e2) {
                  Log.d(TAG, "Unable to end the connection");
                  Toast.makeText(this, "Unable to end the connection", Toast.LENGTH_SHORT).show();
              }
              Log.d(TAG, "Socket creation failed");
              Toast.makeText(this, "connection creation failed", Toast.LENGTH_SHORT).show();
          }
  
          //beginListenForData();
      }
  
  private void writeData(String data) {
      try {
          outStream = btSocket.getOutputStream();
      } catch (IOException e) {
          Log.d(TAG, "Bug BEFORE Sending stuff", e);
      }
  
      String message = data;
      byte[] msgBuffer = message.getBytes();
  
      try {
          outStream.write(msgBuffer);
          Toast.makeText(this, "Data Send Successful..", Toast.LENGTH_SHORT).show();
      } catch (IOException e) {
          Log.d(TAG, "Bug while sending stuff", e);
          Toast.makeText(this, "Data Send Error..", Toast.LENGTH_SHORT).show();
      }
  }
  </code></pre>
  
  <p>}</p>