【问题标题】:Android Java Communication over USB通过 USB 进行 Android Java 通信
【发布时间】:2013-03-18 23:07:06
【问题描述】:

我想通过 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(); 
 }

【问题讨论】:

    标签: java android usb communication


    【解决方案1】:

    我的建议是使用文本文件。

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

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

    当然需要在你的电脑上安装 adb 并在你的手机上允许 USB 调试。

    希望这会有所帮助。

    问候

    【讨论】:

    • 对我帮助很大!!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多