2013-03-18 69 views
1

我想從Android設備發送一個對象/字符串到Java over PC的PC。有可能的? 基本上是USB上的客戶端/服務器。Android上的Java Java通信

實際上,使用模擬器,我可以通過特殊的10.0.2.2地址訪問服務器套接字。 通過無線網絡,我可以訪問192.168.1.X地址。 通過USB,它是如何工作的?

根據這http://android.serverbox.ch/?p=370,我猜這是可能的,但是,我如何在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(); 
} 

回答

0

我的建議是使用文本文件。將文本文件保存在您的SD卡中。然後在你的PC的Java程序中,執行「adb pull」命令。

這種方式,如果您的手機通過USB連接到您的PC,在執行「adb pull」時,文件將從手機中拉到PC。

當然需要在您的電腦上安裝adb,並在手機中允許使用USB調試。

希望這會有所幫助。

Regards

+0

它幫了我很多!謝謝! – leonSantoz 2013-03-21 00:32:17