简体   繁体   中英

How to write and read data from usb on Android?

I need to connect a device to my Android smartphone using the USB port so the phone can read some data from the device and print on the screen of an Android app.

I have read bunch of materials on how to do it, but none seems to work properly. I just know I need to send the device some info so it can send me back some response.

I have made it work perfectly reading from COM port directly on my computer, now how to do it on Android? The documentation of Android hasn't helped me at all, neither some libraries I found googling.

Example of what I've tried with this one: https://github.com/felHR85/UsbSerial

public class MainActivity extends AppCompatActivity {

    UsbDevice device;
    UsbDeviceConnection usbConnection;
    private TextView data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        data = findViewById(R.id.data);

        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        manager.openDevice(device);

        UsbSerialDevice serial = UsbSerialDevice.createUsbSerialDevice(manager.getDeviceList().get(0), usbConnection);

        serial.open();
        serial.setBaudRate(57600);
        serial.setDataBits(UsbSerialInterface.DATA_BITS_8);
        serial.setStopBits(1);
        serial.setParity(UsbSerialInterface.PARITY_NONE);
        serial.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
        byte[] raw = new byte[]{(byte) 0xA5, (byte) 0x10, (byte) 0x02, (byte) 0x1A, (byte) 0x00};
        serial.write(raw);
        serial.read(mCallback);
        serial.close();
    }

    private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {

        @Override
        public void onReceivedData(byte[] arg0)
        {
            data.setText(arg0[0]);
        }

    };
}

but it crashes right on time and I don't really think it's even close to working!

there is a full documentation to use USB HOST OR ACCESSORY MODE for communicating with a USB device ( http://developer.android.com/guide/topics/connectivity/usb/index.html ) or you can use the link below if you like communicating with a device in HOST mode. ( http://developer.android.com/guide/topics/connectivity/usb/host.html ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM