0 USB Background Knowledge
USB is a data communication method, is also a data bus, and is one of the most complex bus.
On the hardware, it is connected with a plug. One side is male (plug), one side is female (receptacle). For example, the socket on the PC is the female, and the USB device is connected to the PC using a male header.
At present, the USB hardware interface is divided into three kinds, the common PC is called type, the original Nokia function Machine ERA interface for mini USB, the current Android phone using micro USB.
Host
USB is the host side control of the entire bus data transmission. There can be only one host on a single USB bus.
OTG
On the Go, which is a mode introduced in USB2.0, presents a new concept called host Negotiation Protocol (hosts negotiation Protocol), allowing two devices to be consulted on who is going to be host.
For more information on USB, please refer to the USB website and the following article:
Http://www.crifan.com/files/doc/docbook/usb_basic/release/html/usb_basic.html
One, the USB in Android
Android support for USB is starting from 3.1, apparently to enhance the external expansion capability of Android tablet. and the use of USB more, is the use of Android in industry. The android industry board will generally provide multiple U ports and multiple serial ports, which are the means and bridges for connecting peripherals. Here's a look at the USB Host for one of the Android USB usage modes.
The relevant classes for USB development are provided under the ANDROID.HARDWARE.USB package.
We need to know Usbmanager, Usbdevice, Usbinterface, Usbendpoint, Usbdeviceconnection, Usbrequest, usbconstants.
1, Usbmanager: Get the USB status, communicate with the connected USB device.
2, USBDEVICE:USB device abstraction, which contains one or more usbinterface, and each usbinterface contains multiple usbendpoint. Host communicates with the usbdeviceconnection and sends and receives data at an endpoint (endpoint) with Usbrequest.
3, Usbinterface: Defines the function set of the device, a usbdevice contains multiple usbinterface, each interface is independent.
4, Usbendpoint:endpoint is the interface communication channel.
5. Usbdeviceconnection:host the connection with device and transmits data in endpoint.
6, USBREQUEST:USB request package. Data can be transferred asynchronously on the usbdeviceconnection. Note that it is only used for asynchronous communication.
7, the definition of Usbconstants:usb constants, corresponding to Linux/usb/ch9.h
Second, USB plug-in event
USB plug-and-unplug is sent as a system broadcast, as long as we register this broadcast.
@OverrideProtectedvoidOnresume () {Super.onresume (); Intentfilter Usbfilter =New Intentfilter (); Usbfilter.addaction (usbmanager.action_usb_device_attached); Usbfilter.addaction (usbmanager.action_usb_device_detached); Registerreceiver (Musbreceiver, Usbfilter); }@OverrideProtectedvoidOnPause () { 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 "); } } };
Third, start the program when USB plug-in
Some scenarios are when a USB plug-in starts a specific program to handle a specific problem.
It is our practice to add a USB insert action to an activity in the manifest.
<intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/></intent-filter> <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/usbfilter" />
Add the filter for the vendor ID and product ID in Usbfilter as follows:
<?xml version="1.0" encoding="utf-8"?><resources> <usb-device vendor-id="1234" product-id="5678" /></resources>
As a result, when the device is connected to the system via USB, the corresponding activity is activated.
Iv. initialization of the Usbmanager
mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
Five. List USB devices
hashmap<string,usbdevice> Devicehashmap = Musbmanager. Getdevicelist (); iterator<usbdevice> 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 ());}
Vi.. USB usage Rights
The use of the USB port by the Android system requires the appropriate permissions, and this permission needs to be given to the user in person.
First we'll check to see if the device in the previous section has been granted permission, and if not, take the initiative to request permission:
//先判断是否为自己的设备 //注意:支持十进制和十六进制 //比如:device.getProductId() == 0x04D2 if(device.getProductId() == 1234 && device.getVendorId() == 5678) { if(mUsbManager.hasPermission(device)) { //do your work } else { mUsbManager.requestPermission(device,mPermissionIntent); } }
We still use the broadcast to get permission to give the situation.
public static final String ACTION_DEVICE_PERMISSION = "com.linc.USB_PERMISSION";
Register a broadcast
mPermissionIntent = PendingIntent.getBroadcast(this,0,new Intent(ACTION_DEVICE_PERMISSION),0); IntentFilter permissionFilter = new IntentFilter(ACTION_DEVICE_PERMISSION); registerReceiver(mUsbReceiver,permissionFilter);
Code for the receiver:
PrivateFinal 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!!!");}}} } };
VII. Communications
Usbdevice has permission, the following can communicate.
Here to use: Usbinterface, Usbendpoint (one in two endpoint, two-way communication), Usbdeviceconnection.
Note: The process of communication cannot be done in the UI thread.
After being authorized, some pre-communication preparations will be made, as follows:
PrivatevoidInitcommunication (Usbdevice device) {tvinfo.append ("Initcommunication in\n");If1234 = = 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 ;} } } }
Send data as follows:
result = mUsbDeviceConnection.bulkTransfer(mUsbEndpointOut, mData, (int)buffSize, 1500);//需要在另一个线程中进行
Viii. Other
As a normal developer, if there is no USB device, then the debug program is a problem.
You can use the Adbtest program to connect two phones or tablets with an OTG cable.
A colleague with a USB device will encode according to the protocol rules of the device. This is used to convert byte to other types, as well as hexadecimal problems.
Concrete analysis of specific problems. This article is a stumbling, it's first here.
Reference:
1, Endpoint Introduction: http://blog.chinaunix.net/uid-25314474-id-3040231.html
from:http://blog.csdn.net/lincyang/article/details/50739342
"Turn" Android Combat Skill 49: USB Host