我想通过 USB 将一个对象/字符串从 Android 设备发送到 Java 中的 PC。有可能的?基本上是一个通过 USB 的客户端/服务器。
实际上,使用模拟器,我可以通过特殊的 10.0.2.2 地址访问服务器套接字。通过 Wi-fi,我可以使用 192.168.1.X 地址访问。通过 USB,它是如何工作的?
根据this,我想这是可能的,但是,我如何在java而不是python中做示例代码?有任何想法吗?
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();
}