概述
private void connect2Usb() {
Logger.t(TAG).d("connect2Usb : connect");
// 1 获取Usbmanager
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
// 2 获取UsbDevice
HashMap<String, UsbDevice> usbDevices = mUsbManager.getDeviceList();
// 3 遍历UsbDevices, 查找USB Device
Set<Map.Entry<String, UsbDevice>> entrySet = usbDevices.entrySet();
UsbDevice usbDevice= null;
for (Map.Entry<String, UsbDevice> entry : entrySet) {
Logger.t(TAG).d("connect2Usb : " + entry.getKey() + "," + entry.getValue());
//find your usb device
if (entry.getValue().getVendorId() == USB_VENDORID) {
usbDevice= entry.getValue();
break;
}
}
if (usbDevice== null) {
Logger.t(TAG).e("no usb devices");
return;
}
if (usbDevice.getInterfaceCount() <= 0) {
Logger.t(TAG).e("no usb devices interface ");
return;
}
//[4] 查找Usb Interface
mUsbInterface = usbDevice.getInterface(0);
Logger.t(TAG).d("usb interface : " + mUsbInterface);
//[5] 查找 Endpoints
for (int i = 0; i < mUsbInterface.getEndpointCount(); i++) {
UsbEndpoint endpoint = mUsbInterface.getEndpoint(i);
if (endpoint.getDirection() == UsbConstants.USB_DIR_IN) {
mUsbEndpointIn = endpoint;
if (mUsbEndpointIn.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
Logger.t(TAG).d("usb bulk transfer");
}
}
if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {
mUsbEndpointOut = endpoint;
}
//for test
int direction = endpoint.getDirection();
Logger.d("direction " + direction);
}
// [5] 检查usb权限
boolean hasPermission = mUsbManager.hasPermission(usbDevice);
if (!hasPermission) {
Logger.t(TAG).e("no usb permission");
//[7] 申请usb权限
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 9898, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_ONE_SHOT);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
mUsbManager.requestPermission(usbDevice, mPermissionIntent);
return;
}
//[8] Open usb Device, create connection
if (mUsbDeviceConnection == null) {
mUsbDeviceConnection = mUsbManager.openDevice(usbDevice);
}
//[9] claim UsbInterface
if (mUsbDeviceConnection != null) {
boolean claimUsb = mUsbDeviceConnection.claimInterface(mUsbInterface, true);
if (claimUsb) {
Logger.t(TAG).d("claimed usbinterface");
}
}
//开始USB Communication。
//...
}
最后
以上就是虚心长颈鹿为你收集整理的Android USB Create Connection 完整过程的全部内容,希望文章能够帮你解决Android USB Create Connection 完整过程所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复