如何在Android中通过USB发送数据?

时间:2016-01-05 15:03:01

标签: android usb

我正在开发Android应用程序,我想通过USB端口发送数据。

我的代码:

    manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();


    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
            ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filter);

    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

    String i = "Test: ";
    while (deviceIterator.hasNext()) {
        device = deviceIterator.next();
        manager.requestPermission(device, mPermissionIntent);
        i += "\n" + "DeviceID: " + device.getDeviceId() + "\n"
                + "DeviceName: " + device.getDeviceName() + "\n"
                + "DeviceClass: " + device.getDeviceClass() + " - "
                + "DeviceSubClass: " + device.getDeviceSubclass() + "\n"
                + "VendorID: " + device.getVendorId() + "\n"
                + "ProductID: " + device.getProductId() + "\n"
                + device.getInterface(0) + " ";

    }

    String a = "VOLT120[CR]";

    byte[] bytes = a.getBytes();
    int TIMEOUT = 0;
    boolean forceClaim = true;

    UsbInterface intf = device.getInterface(0);
    UsbEndpoint endpoint = intf.getEndpoint(0);
    UsbDeviceConnection connection = manager.openDevice(device);
    connection.claimInterface(intf, forceClaim);
    connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT); 

    connection.close();

    textv.setText(i);

我可以从设备上读取一些信息,但是当我发送一些数据时,应用程序会崩溃,我不知道为什么。有人能告诉我,问题在哪里?

0 个答案:

没有答案