Android USB HOST API

Source: Internet
Author: User

Android USB HOST API

Android USB HOST API

Source Code address: http://developer.android.com/guide/topics/connectivity/usb/host.html

Note: It is not very important to translate well. The point is that every sentence will be carefully read during the translation process, in other words, we can achieve a goal of understanding with the idea of translation.

USB Host communication

When your powered Android device processes the USB host mode, it acts as a master device application that powers the USB bus, enumerates connected USB slave devices, and so on. Android 3.1 and later versions support the USB host Mode.

API Overview

Before getting started, it is necessary to understand the classes to be used in the future. The following table describes the USB host APIs contained in the android. hardware. USB package.

Table 1. USB host APIs.

Class

Description

UsbManger

Allow you to enumerate USB slave devices and communicate with them

USB device

Indicates a USB device to obtain its information. Such as interfaces and endpoints.

USB Interface

Represents an interface of a USB slave device. A device can have multiple interfaces for communication.

USB endpoint

Represents an interface endpoint, which is a communication channel. An interface can have one or more endpoints. Generally, the input and output endpoints are used for bidirectional communication with devices.

UsbDeviceConnection

A device connection transmits data through an endpoint, which allows you to send and receive data. The communication mode can be synchronous or asynchronous.

UsbRequest

Represents an asynchronous request for communication through USB deviceconnection.

UsbConstants

Define a USB constant that corresponds to a macro in linux/usb/ch9.h in the linux kernel.

In most cases, when communicating with a USB device, you need to use all the classes here (UsbRequest only uses one request for asynchronous communication ). Generally, USB Manager is used to obtain the USB device. If the device is determined, you need to find the USB interface and USB endpoint used for the communication interface. Once an appropriate endpoint is obtained, enable the USB deviceconnection to communicate with the USB device.

The following table describes the content that needs to be added to the manifest file of the application before using USB host APIs:

Because not all Android power-supply devices support USB host APIs, add Object To indicate that your application uses the android. hardware. usb. host feature.

The minimum SDK version is 12 or later. USB host APIs does not support APIs of earlier versions.

If you want your application to detect a USB device, specify And Android. hardware. usb. action. USB_DEVICE_ATTACHED. The object points to an external XML resource file that describes the filtering information of the USB device you want to detect.

In this XML resource file, the USB device declaration you want to filter Object. The following table describes . Typically, you can filter a group of devices, such as large-capacity storage devices (USB flash drives) or digital cameras, using classes, subclasses, and protocols. You can specify this attribute value completely or not. If no attribute value is specified, each USB device is filtered out. Therefore, if your application has this requirement, you can specify it.


  • vendor-id
  • product-id
  • class
  • subclass
  • protocol(Device or interface)

    Save the resource file to the res/xml/directory. The resource file name (excluding the. xml suffix) must be . XML resource file format:

           
            
            ...                        ...            
                                    
                    
                    
       

    In this example, the following resource files should be saved in res/xml/device_filter.xml, specifying the properties of the USB device to be filtered:

       
           
        
       

    Device work

    When a USB device is connected to Android, the Android system detects whether your application is interested in the USB device or not. You can establish communication with the device. Your application needs to do the following:

    1. Detect USB devices by using intent filters to detect devices connected to users, or enumerate connected USB devices.

    2. If no request has been made before, request the user permission to connect to the USB device.

    3. Communicate with the USB device and read and write data through the interface endpoint.

    Probe Device

    Applications can detect USB devices in two ways, and use intent filters to listen to devices connected to users or enumerate connected USB devices. The former can easily implement automatic detection of devices. You can use enumerative devices to list all connected devices or devices that are not filtered by intent filters.

    Use intent Filter

    The probe device can specify the intent filter to filter android. hardware. usb. action. USB_DEVICE_ATTACHED intent. In addition, you must specify a resource file to describe the USB device, such as product and vendor ID. when the user is connected to the device you are detecting, the system will pop up a dialog box asking whether the user is allowed to start your application. If allowed, your application will be automatically granted the permission to communicate with the device until the device is removed.

    The following example shows how to describe the intent filter:

    ...    
                   
           
       

    The following example shows how to describe the resource file and specify the USB device you are interested in:

       
           
        
       

    In your Activity, you need to obtain the USB device, which represents the device that is detected with the intention. For example:

    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

    Enumerative Device

    If you are interested in the USB device that is currently connected when your application is running, you can enumerate the devices. The getDeviceList () method is used to obtain the hash table of all connected devices. If you want to obtain a device, you can index it based on the keyword of the USB device name.

    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);...  HashMap
       
         deviceList = manager.getDeviceList();UsbDevice device = deviceList.get("deviceName");
       

    If necessary, you can iterate the device from the hash table to process each device in sequence:

    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);...HashMap
       
         deviceList = manager.getDeviceList();Iterator
        
          deviceIterator = deviceList.values().iterator();while(deviceIterator.hasNext()){    UsbDevice device = deviceIterator.next()    //your code}
        
       

    Get permissions to communicate with devices

    Your application must obtain the permission from the user before communicating with the device.

    | Note: if your application uses the intent filter to detect connected USB devices, your application will automatically obtain the permission if the user permits the intent to be processed. Otherwise, you must request permissions from the user before communication.

    In some cases, the request permission is required. For example, your application can enumerate connected USB devices and communicate with the devices. You need to check the permissions before communication. Otherwise, if the user permission is denied, you will receive a running error.

    To apply for permissions, first create a broadcast receiver. When requestPermission () is called, the receiver listens to the broadcast intent. Call requestRermission () to display a dialog box to the user requesting the permission to connect to the device.

    The following code creates a broadcast receiver:

    private static final String ACTION_USB_PERMISSION =    "com.android.example.USB_PERMISSION";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                   }                }                 else {                    Log.d(TAG, "permission denied for device " + device);                }            }        }    }};

    Add the following code to the onCreate () method of the activity to register the broadcast receiver:

    UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);private static final String ACTION_USB_PERMISSION =    "com.android.example.USB_PERMISSION";...mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);registerReceiver(mUsbReceiver, filter);

    In the displayed dialog box, request the permission to connect to the device and call the requestPermission () method:

    UsbDevice device;...mUsbManager.requestPermission(device, mPermissionIntent);

    In the user reply dialog box, the content received by your broadcast receiver is EXTRA_PERMISSION_GRANTED, which is a Boolean representing the answer. Check whether the additional value is true before communication.

    Communicate with devices

    The communication mode can be synchronous or asynchronous. In both cases, you should create a thread to execute all data transmission, and do not block the interface thread. To establish a communication, you need to obtain the USB interface and USB endpoint of the communication device, and apply for an endpoint using USB deviceconnection. Generally, your code should be:

    Check the attributes of the USB device object, such as the product ID, vendor ID, or device category. To identify the device that requires communication. If you determine the device to be connected, retrieve the interface of the device to be connected and the endpoint of the interface. An interface can have one or more endpoints. Generally, there are two-way communication endpoints for each input and output. If the endpoint is determined, Enable USB deviceconnection on the endpoint. Use the bulkTransfer () or controlTransfer () method to provide the data to be transmitted to the endpoint. You need to implement the above operations in other threads to avoid blocking the current main interface thread.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.