簡體   English   中英

如何通過Android設備通過USB通信發送數據?

[英]How to send data via USB communication from Android device?

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


}

您需要首先為Android設備准備驅動程序,例如,如果您的設備使用CP210X芯片組提供USB支持,則應遵循以下步驟: https : //www.silabs.com/documents/public/application-notes/AN809。 PDF格式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM