I'd like to send a object/string from Android device to PC in Java over USB. It is possible? Basically a client/server over USB.
Actually, using the emulator, I can access the server socket via the special 10.0.2.2 address. Over Wi-fi, i can access with 192.168.1.X address. And over USB, how it works?
According to this, I guess it's possible but, how I do the sample code in java instead of python? any ideas?
private Byte[] bytes
private static int TIMEOUT = 5000;
private boolean forceClaim = true
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next()
UsbInterface intf = device.getInterface(0);
UsbEndpoint endpoint = intf.getEndpoint(0);
UsbDeviceConnection connection = mUsbManager.openDevice(device);
connection.claimInterface(intf, forceClaim);
bytes = toByteArray("any path");
connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT);
}
public static byte[] toByteArray(File file) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean threw = true;
InputStream in = new FileInputStream(file);
try {
byte[] buf = new byte[BUF_SIZE];
long total = 0;
while (true) {
int r = in.read(buf);
if (r == -1) {
break;
}
out.write(buf, 0, r);
}
threw = false;
} finally {
try {
in.close();
} catch (IOException e) {
if (threw) {
log.warn("IOException thrown while closing", e);
} else {
throw e;
}
}
}
return out.toByteArray();
}