//看这里,http://www.2cto.com/kf/201212/174105.html
//直接放代码了package com.android.usb;import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;import com.hoho.android.usbserial.driver.FtdiSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import com.hoho.android.usbserial.util.SerialInputOutputManager.Listener;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.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.*;
public class UsbtestActivity extends Activity {
    /** Called when the activity is first created. */
protected TextView txtTips ;
protected EditText edSend ;
protected EditText edReceive ;
protected Button   btnSend  ;

private UsbManager managerme;
private FtdiSerialDriver driver ;
//private SerialInputOutputManager rs232ReadWrite ;
private ReadThread readThread ;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
 
 
//收到 RS232 数据事件
public class  ReadListener  {

public void onRunError(Exception e) {
// TODO Auto-generated method stub

}

public void onNewData( final byte[] data) {
// TODO Auto-generated method stub
UsbtestActivity.this.runOnUiThread(new Runnable() {
public void run() {
UsbtestActivity.this.updateReceivedData( data ) ;
            }
        });
}
};

private ReadListener readListener=new ReadListener();
/*private Listener readListener=new Listener()
{
public void onNewData(final byte[] data)
{
UsbtestActivity.this.runOnUiThread(new Runnable() {
            public void run() {
             String recString=data.toString();
     edReceive.setText(recString) ;
            }
        });
} public void onRunError(Exception e)
{

}
};
*/


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txtTips=(TextView)this.findViewById(R.id.txtTips) ;
        edSend=(EditText)this.findViewById(R.id.edSend) ;
        edReceive=(EditText)this.findViewById(R.id.edReceive) ;
        btnSend=(Button)this.findViewById(R.id.btnSend) ;
        managerme = (UsbManager) getSystemService(Context.USB_SERVICE);
    }
    
@Override
protected void onDestroy() {
btnCloseClick(null);

super.onDestroy();
}
    
//在 调用 getUsb() 时,申请 USB 设备授权时激发
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {     public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        //得到授权
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if(device != null){
                      //call method to set up device communication
                     UsbDeviceConnection connection = managerme.openDevice(device);
         if(connection==null)
         {
         txtTips.setText(txtTips.getText()+"/connection is null");
         }
         else {
         driver=new FtdiSerialDriver(device,connection);
         open232Port();
         txtTips.setText(txtTips.getText()+"/success connect 2");
       }
        
                   }
                } 
                else {
                   // Log.d(TAG, "permission denied for device " + device);
                 txtTips.setText(txtTips.getText()+"/permission denied");
                }
            }
        }
        
        //USB 设备被拔出
        if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (device != null) {
                // call your method that cleans up and closes communication with the device
             btnCloseClick(null);
            }
        }
    }
};
    
private class ReadThread extends Thread{
//private ArrayList<Bundle> mList;
private Boolean IsRun=true ;
private ReadListener mListener;
private static final int BUFSIZ = 4096;
private static final int READ_WAIT_MILLIS = 200;
private final ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ);
//private final byte[] mReadBuffer=new byte[BUFSIZ];


 
public ReadThread(ReadListener listener){
super();
mListener = listener;
}
public void Stop()
{
IsRun=false ;
}
public synchronized ReadListener getListener() {
        return mListener;
}
public void run(){

while(IsRun)
{
if(driver!=null)
{
int len =0;
mReadBuffer.clear();
try {
len=driver.read(mReadBuffer.array(), READ_WAIT_MILLIS);
} catch (Exception e) {
// TODO: handle exception
}

        if (len > 0) {
         final ReadListener listener = getListener();
            if (listener != null) {
             try {
             final byte[] data = mReadBuffer.toString().getBytes("gbk") ;
listener.onNewData(data);
             } catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
            }
            mReadBuffer.clear();
        }
}
}
}
};

//连接到 USB 设备,并打开 RS-232 口
public void getUsb()
    {
    
     HashMap<String, UsbDevice> deviceList = managerme.getDeviceList();
txtTips.setText("size():" + deviceList.size());
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) { UsbDevice tmpDevice = deviceIterator.next();
 //<!-- 梁军 RS232-USB 蕊片 Prolific 0x067B=1659/2303=8963-->
//<!-- DTECH USB-232 线  0x0403=1027/0x6001=24577-->
//if(usd.getVendorId()==1659 && usd.getProductId()==8963 )
if(tmpDevice.getVendorId()==1027 && tmpDevice.getProductId()==24577 )
{
txtTips.setText(txtTips.getText()+"/found usb device ");

UsbDeviceConnection connection=null ;
if( managerme.hasPermission(tmpDevice))
{
connection = managerme.openDevice(tmpDevice);
}

if(connection==null)
{
//授权
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
//注册 USB 授权通知器,如果得到授权,而有消息,从而打开设备
registerReceiver(mUsbReceiver, filter);
//申请授权,等到  mUsbReceiver 成功则创建 driver
managerme.requestPermission(tmpDevice, mPermissionIntent);
}
else
{
driver=new FtdiSerialDriver(tmpDevice,connection);
open232Port();
txtTips.setText(txtTips.getText()+"/success connect 1");

}
//真正打开串口代码在 mUsbReceiver 
return ;
}
}
    }

//当 driver 连接后,打开 232 口,并初始化读写线程
public void open232Port()
{
     if(driver!=null)
     {
try {
     driver.open();
         driver.setParameters(9600, UsbSerialDriver.DATABITS_8, UsbSerialDriver.STOPBITS_1, UsbSerialDriver.PARITY_NONE) ;
         txtTips.setText(txtTips.getText()+"/success open");
         
         readThread=new ReadThread(readListener) ;
         readThread.start();
         //这是一个 interface ,无须调用 run 接口
         //rs232ReadWrite=new SerialInputOutputManager(driver,readListener ) ;
         //rs232ReadWrite.run() ;
         //Thread.sleep(1000);
         //rs232ReadWrite.run();

} catch (Exception e) {
// TODO: handle exception
txtTips.setText(txtTips.getText()+"/open error:"+e.getMessage());
driver=null ;
}
     }
     else
     {
     txtTips.setText(txtTips.getText()+"/connection is null");    
     }
}

    //打开串口
    public void btnOpenClick(View v)
    {
     btnCloseClick(v);
     getUsb();
    }
        //关闭串口
    public void btnCloseClick(View v)
    {
     if(driver!=null)
     {
     /*if(rs232ReadWrite!=null)
     {
     rs232ReadWrite.stop();
     rs232ReadWrite=null;
     }*/
     if(readThread!=null)
     {
     readThread.Stop();
     readThread=null ;
     }
         driver.close();
         driver=null ;
     }
     //edReceive.setText("close click") ;
    }    public void btnSendClick(View v) throws UnsupportedEncodingException
    {
     //edReceive.setText("buton click") ;
     if(driver!=null)
     {
        byte buffer[] = edSend.getText().toString().getBytes("gbk");
        byte endChar[]={0x61,0x62,0x63,0x0d,0x0a} ;
        try {
         driver.write(buffer, 500) ;
         driver.write(endChar, 500) ;
      
         //rs232ReadWrite.writeAsync(buffer) ;
         //rs232ReadWrite.writeAsync(endChar) ;
} catch (Exception e) {
// TODO: handle exception
txtTips.setText(txtTips.getText()+e.getMessage());
}
     }
     else {
     edReceive.setText("driver is null") ;
}
    }
    
    private void updateReceivedData(byte[] data) {
     final String recString=data.toString();
edReceive.setText(recString) ;
    }
    
}