title: How to send data from Arduino to Android
body: <p>I went to a struggle. There are so many tutorials regarding this topic, but I cannot adapt any of those to my project.</p>
  
  <p>What I want to do is simple:
  User press the button in Android (Dialog opens, user enters numbeers, presses ok)
  Arduino compares data and if it matches send one message to Android, if no - another.
  Concept is this.</p>
  
  <p>What I have so far is simple Arduino code</p>
  
  <pre><code>void loop() {
  if (Serial.available() &gt; 0) {  // if the data came
  incomingByte = Serial.read(); // read byte
  if(incomingByte == '0') {
     digitalWrite(LED, LOW);  // if 1, switch LED Off
     Serial.println("LED OFF. Press 1 to LED ON!");  // print message
  }
  if(incomingByte == '1') {
     digitalWrite(LED, HIGH); // if 0, switch LED on
     Serial.println("LED ON. Press 0 to LED OFF!");
     bluetoothSerial.write
  }
  }
  </code></pre>
  
  <p>I found great tutorial for sending data from Arduino to Android, but it's made in Thread mode and I cannot adopt it to my AsyncThread solution. This is the main problem :\</p>
  
  <p>My Android AsyncThread code looks like that:</p>
  
  <pre><code>    private class ConnectBT extends AsyncTask&lt;Void, Void, Void&gt;  // UI thread
  {
      private boolean ConnectSuccess = true; //if it's here, it's almost connected
  
      @Override
      protected void onPreExecute()
      {
          progress = ProgressDialog.show(ConnectedActivity.this, "Connecting...", "Please wait!!!");  //show a progress dialog
      }
  
      @Override
      protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
      {
  
          try
          {
              if (btSocket == null || !isBtConnected)
              {
                  myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
                  BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
                  btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
                  BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                  btSocket.connect();//start connection
              }
          }
          catch (IOException e)
          {
              ConnectSuccess = false;//if the try failed, you can check the exception here
          }
          return null;
      }
      @Override
      protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
      {
          super.onPostExecute(result);
  
          if (!ConnectSuccess)
          {
              Toast.makeText(ConnectedActivity.this, "Connection Failed. Is it a SPP Bluetooth? Try again.", Toast.LENGTH_SHORT).show();
              finish();
          }
          else
          {
              Toast.makeText(ConnectedActivity.this, "Succeed.", Toast.LENGTH_SHORT).show();
              isBtConnected = true;
          }
          progress.dismiss();
      }
  }
  </code></pre>
  
  <p>Solution from the tutorial:</p>
  
  <pre><code> h = new Handler() {
          public void handleMessage(android.os.Message msg) {
              switch (msg.what) {
                  case RECIEVE_MESSAGE:                                                   // if receive massage
                      byte[] readBuf = (byte[]) msg.obj;
                      String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                      sb.append(strIncom);                                                // append string
                      int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
                      if (endOfLineIndex &gt; 0) {                                            // if end-of-line,
                          String sbprint = sb.substring(0, endOfLineIndex);               // extract string
                          sb.delete(0, sb.length());                                      // and clear
                          txtArduino.setText("Data from Arduino: " + sbprint);            // update TextView
                          btnOff.setEnabled(true);
                          btnOn.setEnabled(true);
                      }
                      //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                      break;
              }
          };
      };
  
  
  private 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[256];  // 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);        // Get number of bytes and message in "buffer"
                  h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
              } catch (IOException e) {
                  break;
              }
          }
      }
  
      /* Call this from the main activity to send data to the remote device */
      public void write(String message) {
          Log.d(TAG, "...Data to send: " + message + "...");
          byte[] msgBuffer = message.getBytes();
          try {
              mmOutStream.write(msgBuffer);
          } catch (IOException e) {
              Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
          }
      }
  }
  </code></pre>
  
  <p>Full tutorial can be found here:
  <a href="http://solderer.tv/data-transfer-between-android-and-arduino-via-bluetooth/" rel="nofollow">http://solderer.tv/data-transfer-between-android-and-arduino-via-bluetooth/</a></p>
  
  <p>I can send data from Android to Arduino with no problem. But receiving it.. nope. Any suggestions?</p>
  
  <p>EDITv2</p>
  
  <p>Silly me. I've put handler and thread's code in my activity. And ran</p>
  
  <pre><code>                mConnectedThread = new ConnectedThread();
                  mConnectedThread.start();
  </code></pre>
  
  <p>in AsyncTask background task. I can see valid toast message now.
  Tnx!</p>