在android usb主机上使用usb设备传输数据?

时间:2013-06-05 10:16:58

标签: android usb buffer host data-transfer

我使用Android USB主机连接USB磁盘,我想读写数据到USB磁盘, 但是当我发送bulkTransfer失败了。

收到的缓冲区(strBuf)为空,没有收到字节。我想这可能是发送到usb设备的字节(bytes_w)不对,但我不知道它。

这是我的代码:

private String findInterface() {
    boolean foreClaim = true;
    byte[] bytes_w = null;
    byte[] bytes_r = new byte[1024];
    byte[] send_command = {(byte)0xef, 0x01,(byte) 0x80, 0x01, 0x00,0x00, 0x00,0x00,0x00,0x00 };
    byte[] receive_result = {(byte) 0xef, 0x02};
    int TIMEOUT = 0;
    StringBuffer strBuf_send = new StringBuffer();
    StringBuffer strBuf_receive = new StringBuffer();
    if ( device == null ) {
        return " " + -2;
    }else {

            intf = device.getInterface(0);

            epIN = intf.getEndpoint(0); //0 -in read
            epOUT = intf.getEndpoint(1); // 1- out write
            connection = uManager.openDevice(device);

            if ( !connection.claimInterface(intf, foreClaim)) {
                connection.close();
            }
            bytes_w = send_command;
            int w= connection.bulkTransfer(epOUT, bytes_w, bytes_w.length, 3000);

            int r = connection.bulkTransfer(epIN, bytes_r, bytes_r.length, 3000); 


            for (int i=0; i<bytes_r.length; i++) {
                if (bytes_r[i] != 0) {
                    strBuf_send.append(bytes_r[i] + "," );
                }

            }

            bytes_w = receive_result;
            int w2= connection.bulkTransfer(epOUT, bytes_w, bytes_w.length, 3000);
            int r2 = connection.bulkTransfer(epIN, bytes_r, bytes_r.length, 3000); 
            // read returned buffer 
            for (int i=0; i<bytes_r.length; i++) {
                if (bytes_r[i] != 0) {
                    strBuf_receive.append(bytes_r[i] + "," );
                }


            }
            return " write: " + w + ", read:" + r + "read buffer " + strBuf_send.toString() +
                    " write: " + w2 + ", read:" + r2 + "read buffer " + strBuf_receive.toString() ; 

}

1 个答案:

答案 0 :(得分:1)

我无法确定您是否设置了发送和接收数据的波特率。 当我尝试在我的应用程序中设置通信时,这是我第一次遇到的问题。

如果您希望波特率为9600,请编写以下内容:

connection.controlTransfer(0x40, 0x03, 0x4138, 0, null, 0, 0); // Sets the baudrate to 9600