Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android實戰技巧之四十九:USB Host通信全解析

編輯:關於 Android 開發

Android實戰技巧之四十九:USB Host通信全解析

零、USB背景知識

USB既是一種數據通信方式,也是一種數據總線,而且是其中最複雜的總線之一。硬體上,它靠插頭連接,一邊是公頭(plug),一邊是母頭(receptacle)。例如PC上的插座就是母頭,USB設備則用公頭與PC相連。

目前USB硬體接口大致分三種:普通PC上使用的Type-A;早期諾基亞功能機時代的Mini USB;以及當今Android手機普遍採用的Micro USB。

Host:USB由Host端控制整個總線的數據傳輸,單條USB總線上只能有一個Host。

OTG:即On The Go,是USB 2.0引入的一種模式,提出了「主機協商協議」(Host Negotiation Protocol),允許兩個設備之間商量由誰來當Host。

一、Android中的USB

Android對USB的支持始於3.1版本,顯然是為了增強平板對外擴展能力;而在工業領域,USB的使用更為廣泛。Android工業板通常會提供多個USB口與多個串口,作為連接外設的橋樑。下面聚焦Android USB使用模式之一的USB Host。

android.hardware.usb包提供了USB開發相關的類,我們需要了解:UsbManager、UsbDevice、UsbInterface、UsbEndpoint、UsbDeviceConnection、UsbRequest、UsbConstants。

1、UsbManager:獲取USB狀態,並與連接的USB設備通信。

2、UsbDevice:USB設備的抽象,包含一個或多個UsbInterface,每個UsbInterface又包含多個UsbEndpoint。Host與其通信時,先打開UsbDeviceConnection,再透過UsbRequest在端點(endpoint)上收發數據。

3、UsbInterface:定義設備的功能集,一個UsbDevice可包含多個彼此獨立的Interface。

4、UsbEndpoint:Interface的通信通道。

5、UsbDeviceConnection:Host與Device建立的連接,並在endpoint上傳輸數據。

6、UsbRequest:USB請求包,可在UsbDeviceConnection上同步或異步傳輸數據。

7、UsbConstants:USB常量定義,對應linux/usb/ch9.h。

二、USB插入事件

USB的插入與拔出是以系統廣播的形式發送的,只要註冊這個廣播即可。

  @Override protected void onResume() { super.onResume(); IntentFilter usbFilter = new IntentFilter(); usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); registerReceiver(mUsbReceiver, usbFilter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(mUsbReceiver); } private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); tvInfo.append("BroadcastReceiver in\n"); if(UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { tvInfo.append("ACTION_USB_DEVICE_ATTACHED\n"); } else if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { tvInfo.append("ACTION_USB_DEVICE_DETACHED\n"); } } };

三、USB插入時啟動程序

有些場景是:USB一插入就啟動特定程序來處理特定任務。做法是在Manifest中為某個Activity加入USB插入的action。

 <intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"> </action></intent-filter> <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/usbfilter"></meta-data>

在usbfilter中加入廠商id與產品id的過濾:

 <resources> <usb-device vendor-id="1234" product-id="5678"> </usb-device></resources>

這樣一來,當該型號設備透過USB連接到系統時,對應的Activity便會被啟動。

四、UsbManager的初始化

 mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);

五、列出USB設備

  HashMap deviceHashMap = mUsbManager.getDeviceList(); Iterator iterator = deviceHashMap.values().iterator(); while (iterator.hasNext()) { UsbDevice device = iterator.next(); tvInfo.append("\ndevice name: "+device.getDeviceName()+"\ndevice product name:" +device.getProductName()+"\nvendor id:"+device.getVendorId()+ "\ndevice serial: "+device.getSerialNumber()); }

六、USB使用權限

安卓系統對USB口的使用需要相應權限,而這個權限要用戶親自授予。首先確認上一節中的device是否已獲得權限,若沒有則主動申請:

  //先判斷是否為自己的設備 //注意:支持十進制和十六進制 //比如:device.getProductId() == 0x04D2 if(device.getProductId() == 1234 && device.getVendorId() == 5678) { if(mUsbManager.hasPermission(device)) { //do your work } else { mUsbManager.requestPermission(device,mPermissionIntent); } } 

我們仍然用廣播來接收權限授予結果。

 public static final String ACTION_DEVICE_PERMISSION = "com.linc.USB_PERMISSION";

註冊廣播:

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

接收器代碼:

  private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); tvInfo.append("BroadcastReceiver in\n"); if (ACTION_DEVICE_PERMISSION.equals(action)) { synchronized (this) { UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { if (device != null) { tvInfo.append("usb EXTRA_PERMISSION_GRANTED"); } } else { tvInfo.append("usb EXTRA_PERMISSION_GRANTED null!!!"); } } } } };

七、通信

拿到權限後,就可以進行通信了。這裡會用到UsbInterface、UsbEndpoint(一進一出兩個端點,構成雙向通信)以及UsbDeviceConnection。注意:通信過程不能在UI線程中進行。授權後先做一些通信前的準備:

 private void initCommunication(UsbDevice device) { tvInfo.append("initCommunication in\n"); if(1234 == device.getVendorId() && 5678 == device.getProductId()) { tvInfo.append("initCommunication in right device\n"); int interfaceCount = device.getInterfaceCount(); for (int interfaceIndex = 0; interfaceIndex < interfaceCount; interfaceIndex++) { UsbInterface usbInterface = device.getInterface(interfaceIndex); if ((UsbConstants.USB_CLASS_CDC_DATA != usbInterface.getInterfaceClass()) && (UsbConstants.USB_CLASS_COMM != usbInterface.getInterfaceClass())) { continue; } for (int i = 0; i < usbInterface.getEndpointCount(); i++) { UsbEndpoint ep = usbInterface.getEndpoint(i); if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (ep.getDirection() == UsbConstants.USB_DIR_OUT) { mUsbEndpointIn = ep; } else { mUsbEndpointOut = ep; } } } if ((null == mUsbEndpointIn) || (null == mUsbEndpointOut)) { tvInfo.append("endpoint is null\n"); mUsbEndpointIn = null; mUsbEndpointOut = null; mUsbInterface = null; } else { tvInfo.append("\nendpoint out: " + mUsbEndpointOut + ",endpoint in: " + mUsbEndpointIn.getAddress()+"\n"); mUsbInterface = usbInterface; mUsbDeviceConnection = mUsbManager.openDevice(device); break; } } } }

發送數據:

 result = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, mData, (int)buffSize, 1500);//需要在另一個線程中進行

八、其他

作為一名普通開發者,如果手頭沒有USB設備,調試程序就成了難題。可以借助AdbTest程序,用OTG線連接兩台手機或平板來試試。有USB設備的同事,則要依照設備的通信協議規則去編碼,這裡面會牽涉byte與其他類型的轉換,以及十六進位處理等問題。具體問題具體分析,這篇就先寫到這裡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved