如何通过USB设备从Android设备发送数据?

时间:2016-02-10 16:06:33

标签: java android usb

我想通过USB通信从我的Android应用程序向设备发送数据(字符串)。我是Android开发的初学者,所以我遵循了本教程:http://developer.android.com/guide/topics/connectivity/usb/host.html 不知何故,与设备通信的部分不起作用,不会向设备发送任何文本。我也尝试用

发送数据
connection.controlTransfer(0x40, 0x03, 0x2580, 0, null, 0, 0);

ByteBuffer buffer = ByteBuffer.allocate(bytes.length+1);
UsbRequest request = new UsbRequest();
buffer.put(bytes);

request.initialize(connection, epOut);
request.queue(buffer, bytes.length);

但没有任何效果。 我真的不明白,我怎么能从我的Android应用程序发送一个简短的文本,例如“@V”到设备。

你能帮我解决一下代码中的问题吗?提前谢谢。

这是我的MainActivity类:

public class MainActivity extends AppCompatActivity {

UsbDevice device;
Button bShow;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
UsbManager mUsbManager;
PendingIntent mPermissionIntent;
Boolean isDevice = true;
TextView tvTest;
String sendText = "@V";
private byte[] bytes;
private static int TIMEOUT = 0;
private boolean forceClaim = true;
int controlTransferResult;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvTest = (TextView) findViewById(R.id.textView);
    showData();

}

public void showData(){
    bShow= (Button)findViewById(R.id.button);
    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    Log.e("MainActivity", "DeviceList:" + deviceList.toString());
    if(deviceList.toString().equals("{}")){
        Toast.makeText(MainActivity.this,"No USB device found!", Toast.LENGTH_SHORT).show();
        return;
    }else{
        tvTest.setText(deviceList.toString());
    }
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    //while(deviceIterator.hasNext()) {
        device = deviceIterator.next();
    //}

    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filter);
    mUsbManager.requestPermission(device, mPermissionIntent);

    bShow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Toast.makeText(MainActivity.this, device.getDeviceName() + "\n"
                    + device.getManufacturerName() + "\n"
                    + device.getProductName() + "\n"
                    + device.getVendorId() + "\n"
                    + device.getDeviceId() + "\n"
                    + "i=" + controlTransferResult, Toast.LENGTH_SHORT).show();
        }
    });
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if(device != null){
                        //call method to set up device communication
                        UsbInterface intf = device.getInterface(0);
                        UsbEndpoint epOut = null;
                        UsbEndpoint epIn = null;
                        // look for our bulk endpoints
                        for (int i = 0; i < intf.getEndpointCount(); i++) {
                            UsbEndpoint ep = intf.getEndpoint(i);
                            //Log.d(TAG, "EP " + i + ": " + ep.getType());

                            if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                                if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                                    epOut = ep;

                                } else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                                    epIn = ep;

                                }
                            }
                        }
                        if (epOut == null || epIn == null) {
                            throw new IllegalArgumentException("Not all endpoints found.");
                        }
                        //UsbEndpoint endpoint = intf.getEndpoint(1);
                        UsbDeviceConnection connection = mUsbManager.openDevice(device);
                        connection.claimInterface(intf, forceClaim);
                        bytes = sendText.getBytes();
                        controlTransferResult = connection.controlTransfer(0x40, 0x03, 0x2580, 0, null, 0, 0);//baudrate 9600
                        //int res = connection.bulkTransfer(epOut, bytes, bytes.length, TIMEOUT); //do in another thread
                        ByteBuffer buffer = ByteBuffer.allocate(bytes.length+1);
                        UsbRequest request = new UsbRequest();
                        buffer.put(bytes);

                        request.initialize(connection, epOut);
                        request.queue(buffer, bytes.length);
                    }
                }
                else {
                    Log.d("MyActivity", "permission denied for device " + device);
                }
            }
        }
    }
};


}

1 个答案:

答案 0 :(得分:0)

您需要先为Android设备准备驱动程序,例如,如果您的设备使用CP210X芯片组获取USB支持,则应遵循以下步骤:https://www.silabs.com/documents/public/application-notes/AN809.pdf

相关问题