Send a simple picture through USB Host on Android

184 views Asked by At

I have already tried the program using code snippets on https://developer.android.com/guide/topics/connectivity/usb/host.html

I am able to discover the UsbDevice connected, but still have no clue how to establish a connection so that I can pass a simple jpeg file and receive it on the receiver end. Any guidance would be appreciated.

1

There are 1 answers

0
Distwo On

I m not sure where exactly you are stuck but the link you posted seems to have all the info needed. Once you have a hold of your UsbDevice you need to request permission to communicate (see Obtaining permission to communicate with a device). You can then transfer data using the following code:

private Byte[] bytes;  //Convert your jpeg into a byte array and load it in this variable.
private static int TIMEOUT = 0;
private boolean forceClaim = true;

...

UsbInterface intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(0);
UsbDeviceConnection connection = mUsbManager.openDevice(device); //this opens the connection
connection.claimInterface(intf, forceClaim);
connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT); //this actually sends the bytes to the other device.

On the other side you will need to convert your byte array back to a jpeg

See this code for a full sample.