Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于USB的Android-Java通信_Java_Android_Usb_Communication - Fatal编程技术网

基于USB的Android-Java通信

基于USB的Android-Java通信,java,android,usb,communication,Java,Android,Usb,Communication,我想用Java通过USB从Android设备向PC发送一个对象/字符串。有可能吗? 基本上是通过USB的客户机/服务器 实际上,使用emulator,我可以通过特殊的10.0.2.2地址访问服务器套接字。 通过Wi-fi,我可以访问192.168.1.X地址。 通过USB,它是如何工作的 根据,我想这是可能的,但是,我如何用java而不是python编写示例代码呢?有什么想法吗 private Byte[] bytes private static int TIMEOUT = 5000; pri

我想用Java通过USB从Android设备向PC发送一个对象/字符串。有可能吗? 基本上是通过USB的客户机/服务器

实际上,使用emulator,我可以通过特殊的10.0.2.2地址访问服务器套接字。 通过Wi-fi,我可以访问192.168.1.X地址。 通过USB,它是如何工作的

根据,我想这是可能的,但是,我如何用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(); 
 }

我的建议是使用文本文件

将文本文件保存在SD卡中。然后在PC java程序中,执行adb pull命令

这样,如果您的手机通过USB连接到PC,则在adb pull执行时,文件将从手机拉到PC

当然,你需要在你的电脑和USB调试允许在你的手机adb

希望这有帮助


问候

这对我帮助很大!!谢谢