我想通过USB在Java中从Android设备向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();
}
发布于 2013-03-19 09:32:02
我的建议是使用文本文件。
将文本文件保存在SD卡中。然后在您的PC java程序中,执行adb pull
命令。
这样,如果您的手机通过USB连接到您的PC,文件将在adb pull
执行时从手机拉到PC。
当然,需要有adb在您的PC和USB调试允许在您的手机。
希望这能有所帮助。
问候
https://stackoverflow.com/questions/15488653
复制相似问题