title: How to receive data in android from serial port
body: <p>I am creating an android application for serial communication. Here i used FTDI cable for serial communication between android device and pc. To display data in my pc i am using hyper terminal.I created an successful connection between android and my pc using FTDI and i was sending data from android device to my pc successfully with baudrate of 19200. But here i want to receive the data which was sent by pc to android using serial cable that is bidirectional communication.Any one tell me how to do that. i did some code but it wont works please help me...</p>
  
  <p>This is my usb driver</p>
  
  <pre><code>package com.example.democomm;
  
  import java.util.HashMap;
  import java.util.Iterator;
  import android.app.Activity;
  import android.app.PendingIntent;
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.content.IntentFilter;
  import android.hardware.usb.UsbConstants;
  import android.hardware.usb.UsbDevice;
  import android.hardware.usb.UsbDeviceConnection;
  import android.hardware.usb.UsbEndpoint;
  import android.hardware.usb.UsbInterface;
  import android.hardware.usb.UsbManager;
  import android.util.Log;
  public class UsbDriver
  {
  
      private final Context mApplicationContext;
      private final UsbManager mUsbManager;
      @SuppressWarnings("unused")
      private final UsbConnectionHandler mConnectionHandler;
      private final int VID;
      private final int PID;
      protected static final String ACTION_USB_PERMISSION = "ch.serverbox.android.USB";
      public static int Device_Exception;
      public static UsbDevice Device_Details;
      public static UsbEndpoint Data_In_End_Point = null;
      public static UsbEndpoint Data_Out_End_Point = null;
      public static UsbDeviceConnection USB_Device_Connection;
  
      public UsbDriver(Activity parentActivity,UsbConnectionHandler connectionHandler, int vid, int pid) 
      {
          mApplicationContext = parentActivity.getApplicationContext();
          mConnectionHandler = connectionHandler;
          mUsbManager = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
          VID = 6790;
          PID = 29987;
          Device_Exception = 0;
      //  init();
          Check_Devices();
      }
  
      private void Check_Devices() 
      {
          @SuppressWarnings("unused")
          int j=0;
          HashMap&lt;String, UsbDevice&gt; devlist = mUsbManager.getDeviceList();
          Iterator&lt;UsbDevice&gt; deviter = devlist.values().iterator();
          Device_Details = null;
          if (devlist.size() != 0) 
          {
  
              while (deviter.hasNext()) 
              {
                  Device_Details = deviter.next();
  
                  if (Device_Details.getVendorId() == VID &amp;&amp; Device_Details.getProductId() == PID)
                  {
                      if (!mUsbManager.hasPermission(Device_Details))
                      {
                          onPermissionDenied(Device_Details);
                      }
                      else 
                      {
                          UsbDeviceConnection conn = mUsbManager.openDevice(Device_Details);
                          if (!conn.claimInterface(Device_Details.getInterface(0), true))
                          {
                              return;
                          }
  
                          conn.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
                          conn.controlTransfer(0x40, 0, 1, 0, null, 0, 0);// clear Rx
                          conn.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
                          conn.controlTransfer(0x40, 0x03, 0x809C, 0, null, 0, 0);
                          USB_Device_Connection=conn; 
                          Data_In_End_Point = null;
                          Data_Out_End_Point = null;
  
                          UsbInterface usbIf = Device_Details.getInterface(0);
                          for (int i = 0; i &lt; usbIf.getEndpointCount(); i++) 
                          {
                              if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) 
                              {
                                  if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
  
                                      Data_In_End_Point = usbIf.getEndpoint(i);
                                  else
                                      Data_Out_End_Point = usbIf.getEndpoint(i);
                              }
                          }
                          if (Data_In_End_Point == null || Data_Out_End_Point == null)
  
                              Device_Exception = 2;
                      }
                      break;
                  }j++;
              }
              if (Device_Details == null)
              {
                  Device_Exception = 3;
                  return;
              }
          }
          else 
          {
              Device_Exception = 1;
              return;
          }
  
      }
      public void onPermissionDenied(UsbDevice d) 
      {
          UsbManager usbman = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
  
          PendingIntent pi = PendingIntent.getBroadcast(mApplicationContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
  
          mApplicationContext.registerReceiver(mPermissionReceiver,new IntentFilter(ACTION_USB_PERMISSION));
  
          usbman.requestPermission(d, pi);
      }
  
  
          private class PermissionReceiver extends BroadcastReceiver 
          {
              private final IPermissionListener mPermissionListener;
  
              public PermissionReceiver(IPermissionListener permissionListener) 
              {
                  mPermissionListener = permissionListener;
              }
  
          @Override
          public void onReceive(Context context, Intent intent) 
          {
              mApplicationContext.unregisterReceiver(this);
  
              if (intent.getAction().equals(ACTION_USB_PERMISSION)) 
              {
                  if (!intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) 
                  {
                      mPermissionListener.onPermissionDenied((UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
                  } 
                  else 
                  {
                      l("Permission granted");
                      UsbDevice dev = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                      if (dev != null)
                      {
                          if (dev.getVendorId() == VID &amp;&amp; dev.getProductId() == PID) 
                          {
                              Check_Devices() ;
                          }
                      }
                      else
                      {
                          e("device not present!");
                      }
                  }
              }
          }
  
      }
  
      // MAIN LOOP
  
      // END MAIN LOOP
      private BroadcastReceiver mPermissionReceiver = new PermissionReceiver(new IPermissionListener() 
      {
                  @Override
                  public void onPermissionDenied(UsbDevice d) 
                  {
                      l("Permission denied on " + d.getDeviceId());
                  }
              });
  
      private static interface IPermissionListener 
      {
          void onPermissionDenied(UsbDevice d);
      }
  
      public final static String TAG = "USBController";
  
      private void l(Object msg) 
      {
          Log.d(TAG, "&gt;==&lt;" + msg.toString() + " &gt;==&lt;");
      }
  
      private void e(Object msg) 
      {
          Log.e(TAG, "&gt;==&lt; " + msg.toString() + " &gt;==&lt;");
      }
  }
  </code></pre>
  
  <p>This is my main activity</p>
  
  <pre><code>package com.example.democomm;
  
  import java.nio.ByteBuffer;
  import java.util.HashMap;
  import android.app.ActionBar;
  import android.app.Activity;
  import android.content.Intent;
  import android.content.SharedPreferences;
  import android.graphics.Typeface;
  import android.hardware.usb.UsbDevice;
  import android.hardware.usb.UsbDeviceConnection;
  import android.hardware.usb.UsbEndpoint;
  import android.hardware.usb.UsbInterface;
  import android.hardware.usb.UsbManager;
  import android.hardware.usb.UsbRequest;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Button;
  import android.widget.CheckBox;
  import android.widget.EditText;
  import android.widget.TextView;
  import android.widget.Toast;
  public class MainActivity extends Activity
  {
  
      public static final int targetVendorID = 6790;      
      public static final int targetProductID = 29987;
      public  UsbManager manager;
      public  UsbDeviceConnection usbDeviceConnection;
      public  UsbInterface usbInterfaceFound = null;
      public  UsbEndpoint endpointOut = null;
      public  UsbEndpoint endpointIn = null;
      public  UsbDevice usbdevice,device_details;
      public  UsbEndpoint listusbendpoint;
  
      public static final String PREFS_NAME = "LoginPrefs";
      HashMap&lt;String, UsbDevice&gt; devicelist= null;
      int selectedendpoint; 
      static int Coil_No;
      private static final int VID = 6790;
      private static final int PID = 29987;
      private static UsbDriver Usb_Driver_class;
      ActionBar actionbar;
      UsbConnectionHandler connectionHandler;
      public static UsbDriver USB_Driver_Child;
      public static boolean Communication_Failed,Frame_Ok,Total_Frame_Decoded;
      static byte[] Communication_Byte;
      public SharedPreferences loginpreferences;
      public SharedPreferences.Editor loginpreferenceseditor;
      public boolean savelogin;
      public String Password;
      Button sample_button;
      public EditText receive_Data;
      CheckBox remember_me;
      Typeface custom_font;
      String i = "";
      Intent i2;
      CheckBox show_password;
      String ProcID;
      String User_Name_string,password_string;
      TextView title,username_txt,password_txt,company_name;
      ByteBuffer buffer;
      Button signin;
      EditText dialog_username,dialog_password,dialog_confirm;
  
      static byte[] sample;
      static boolean Communication_Ok;
      public static float []Wave_Form_Data=new float[1500];
      public static float []Wave_Form_Data_1=new float[1500];
      public static float Respsonse_Time,Drive_Voltage;
      static int Sequence_No,Response_Time;
  
      @Override
      protected void onCreate(Bundle savedInstanceState)
      {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          receive_Data = (EditText)findViewById(R.id.edit_receive);
          signin = (Button)findViewById(R.id.button1);
          signin.setOnClickListener(new View.OnClickListener() 
          {
  
              @SuppressWarnings("static-access")
              @Override
              public void onClick(View v) 
              {
                      Communication_Byte=new byte[1];
  
  
                          if(Check_Devices_Available()==true)
                          {   
                              int Packet_Size = USB_Driver_Child.Data_In_End_Point.getMaxPacketSize();
                              Toast.makeText(MainActivity.this,""+Packet_Size, Toast.LENGTH_LONG).show();
                              Receive.start();
                              Communication_Ok=false;
                              for(int i=0;(i&lt;5 &amp;&amp; Communication_Ok!=true);i++)    
                              Send_Communication_Check_Command();
  
                              if(Communication_Ok)
                                  Toast.makeText(MainActivity.this, "Communication Successfully Established", 1000).show();
                              else
                                  Toast.makeText(MainActivity.this, "Communication Failure", 10000).show();
                          }
                      }
                  });
              }
  
  
  
  
  
      public boolean  Check_Devices_Available() 
      {
          Usb_Driver_class = new UsbDriver(this, connectionHandler, VID, PID);
  
          if(USB_Driver_Child.Device_Exception==0)
          {
  
              if(USB_Driver_Child.USB_Device_Connection==null || USB_Driver_Child.Data_Out_End_Point==null)
              return false;   
  
              Toast.makeText(MainActivity.this,"Device Found", 1000).show();  
              return true;
          }
          else if(USB_Driver_Child.Device_Exception==1)
          {
              Toast.makeText(MainActivity.this,"No Devices Attached ", Toast.LENGTH_LONG).show(); 
              return false;
          }
          else if(USB_Driver_Child.Device_Exception==2)
          {
              Toast.makeText(MainActivity.this,"Device Found,But No End Points", Toast.LENGTH_LONG).show();   
              return false;
          }
          else if(USB_Driver_Child.Device_Exception==3)
          {
              Toast.makeText(MainActivity.this,"Unable to Open Device", Toast.LENGTH_LONG).show();    
              return false;
          }
          return false;   //un known exception
      }
  
  Thread Receive  = new Thread(new Runnable()
      {
  
      @SuppressWarnings("unused")
      @Override
      public void run() 
      {
          //Sequence_No=0;
          buffer = ByteBuffer.allocate(64);
          sample = new byte[64];
  
          UsbRequest request = new UsbRequest();
          int i,j;
          byte [] datarx=new byte[1]; 
  
          char q;
          while (true) 
          {
          request.initialize(USB_Driver_Child.USB_Device_Connection, USB_Driver_Child.Data_In_End_Point);
          request.queue(buffer, 64);
          if (USB_Driver_Child.USB_Device_Connection.requestWait() == request) 
          {
  
              //UsbDriver.USB_Device_Connection.bulkTransfer(UsbDriver.Data_In_End_Point,datarx, datarx.length, 0);   
              sample=buffer.array();
                  for(i=0;i&lt;64;i++)
                  {
                      receive_Data.setText(sample.toString());
                      if(sample[i]=='&amp;')
                          {
                              Communication_Ok=true;
                              break;
                          }
                  }
  
  
          }
        }
  
  
  
  
      }
    });
  
  
  private static void Send_Communication_Check_Command() 
  {
      long i,j;
  
      Communication_Byte[0]='&amp;';
      UsbDriver.USB_Device_Connection.bulkTransfer(UsbDriver.Data_Out_End_Point,Communication_Byte, 1, 0);
      for(i=0;(i&lt;1000 &amp;&amp; Communication_Ok!=true) ;i++)    
      for(j=0;(j&lt;1000 &amp;&amp; Communication_Ok!=true);j++);
  }
  
  
  
  
  
   }
  </code></pre>
  
  <p>Here Inside the thread i wrote the code for receiving data which was not working</p>