Create your own awesome maps

Even on the go

with our free apps for iPhone, iPad and Android

Get Started

Already have an account?
Log In

android.hardware.usb.UsbManager by Mind Map: android.hardware.usb.UsbManager
0.0 stars - reviews range from 0 to 5

android.hardware.usb.UsbManager

This class (UsbManager) comes from android.hardware.usb package.  This class allows you to access the state of USB and communicate with USB devices. Currently only host mode is supported in the public API.  You can obtain an instance of this class by calling Context.getSystemService() UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

Public Methods

getAccessoryList()

Returns a list of currently attached USB accessories.

returns UsbAccesory []

getDeviceList()

Returns a HashMap containing all USB devices currently attached.

returns HashMap<String, UsbDevice>

hasPermission(UsbDevice device)

Returns true if the caller has permission to access the device.

returns boolean

hasPermission(UsbAccessory accessory)

Returns true if the caller has permission to access the accessory.

returns boolean

openAccessory(UsbAccessory accessory)

Opens a file descriptor for reading and writing data to the USB accessory.

returns ParcelFileDescriptor

openDevice(UsbDevice device)

Opens the device so it can be used to send and receive data using UsbRequest.

returns UsbDeviceConnection

requestPermission(UsbDevice device, PendingIntent pi)

Requests temporary permission for the given package to access the device.

returns void

requestPermission(UsbAccessory accessory, PendingIntent pi)

Requests temporary permission for the given package to access the accessory.

returns void

Constants

ACTION_USB_ACCESSORY_ATTACHED

The link shows an example on how to use this constant.

ACTION_USB_ACCESSORY_DETACHED

The link shows an example on how to use this constant.

ACTION_USB_DEVICE_ATTACHED

A link of an example on how to detect a USB device and an example on how to declare the intent filter below. ...> ... android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" />

ACTION_USB_DEVICE_DETACHED

Link with an example on how to detach a USB device.

EXTRA_ACCESSORY

EXTRA_DEVICE

The following example shows how to declare the corresponding resource file that specifies the USB devices that you're interested in: xml version="1.0" encoding="utf-8"?>     vendor-id="1234" product-id="5678" /> In your activity, you can obtain the UsbDevice that represents the attached device from the intent like this: UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

EXTRA_PERMISSION_GRANTED

android.hardware.usb

When communicating with a USB device. In general, you obtain a UsbManager to retrieve the desired UsbDevice. When you have the device, you need to find the appropriate UsbInterface and the UsbEndpoint of that interface to communicate on. Once you obtain the correct endpoint, open a UsbDeviceConnection to communicate with the USB device.

class UsbManager

class UsbDevice

class UsbInterface

class UsbEndpoint

class UsbDeviceConnection

class UsbRequest

Is only required if you are doing asynchronous communication.

class UsbConstants

Manifest Requirements for USB use

The following list describes what you need to add to your application's manifest file before working with the USB host APIs: Because not all Android-powered devices are guaranteed to support the USB host APIs, include a element that declares that your application uses the android.hardware.usb.host feature. Set the minimum SDK of the application to API Level 12 or higher. The USB host APIs are not present on earlier API levels. If you want your application to be notified of an attached USB device, specify an and element pair for the android.hardware.usb.action.USB_DEVICE_ATTACHED intent in your main activity. The element points to an external XML resource file that declares identifying information about the device that you want to detect. In the XML resource file, declare elements for the USB devices that you want to filter. The following list describes the attributes of . In general, use vendor and product ID if you want to filter for a specific device and use class, subclass, and protocol if you want to filter for a group of USB devices, such as mass storage devices or digital cameras. You can specify none or all of these attributes. Specifying no attributes matches every USB device, so only do this if your application requires it: vendor-id product-id class subclass protocol (device or interface) Save the resource file in the res/xml/ directory. The resource file name (without the .xml extension) must be the same as the one you specified in the element. The format for the XML resource file is in the example below.

Manifest and resource file examples

The following example shows a sample manifest and its corresponding resource file: ...>     android:name="android.hardware.usb.host" />     android:minSdkVersion="12" />     ...             ...>             ...                             android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />                         android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"                 android:resource="@xml/device_filter" />             In this case, the following resource file should be saved in res/xml/device_filter.xml and specifies that any USB device with the specified attributes should be filtered: xml version="1.0" encoding="utf-8"?>     vendor-id="1234" product-id="5678" class="255" subclass="66" protocol="1" />

Working with USB Devices

Discovery

Using an intent filter

Enumerating Devices

Obtaining Permission to Communicate

Before communicating with the USB device, your applicaton must have permission from your users. Note: If your application uses an intent filter to discover USB devices as they're connected, it automatically receives permission if the user allows your application to handle the intent. If not, you must request permission explicitly in your application before connecting to the device. Explicitly asking for permission might be neccessary in some situations such as when your application enumerates USB devices that are already connected and then wants to communicate with one. You must check for permission to access a device before trying to communicate with it. If not, you will receive a runtime error if the user denied permission to access the device. To explicitly obtain permission, first create a broadcast receiver. This receiver listens for the intent that gets broadcast when you call requestPermission(). The call to requestPermission() displays a dialog to the user asking for permission to connect to the device. The following sample code shows how to create the 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);                 }             }         }     } }; To register the broadcast receiver, add this in your onCreate() method in your activity: 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); To display the dialog that asks users for permission to connect to the device, call the requestPermission() method: UsbDevice device; ... mUsbManager.requestPermission(device, mPermissionIntent); When users reply to the dialog, your broadcast receiver receives the intent that contains the EXTRA_PERMISSION_GRANTED extra, which is a boolean representing the answer. Check this extra for a value of true before connecting to the device.

Communicating

Communication with a USB device can be either synchronous or asynchronous. In either case, you should create a new thread on which to carry out all data transmissions, so you don't block the UI thread. To properly set up communication with a device, you need to obtain the appropriate UsbInterface and UsbEndpoint of the device that you want to communicate on and send requests on this endpoint with a UsbDeviceConnection. In general, your code should: Check a UsbDevice object's attributes, such as product ID, vendor ID, or device class to figure out whether or not you want to communicate with the device. When you are certain that you want to communicate with the device, find the appropriate UsbInterface that you want to use to communicate along with the appropriate UsbEndpoint of that interface. Interfaces can have one or more endpoints, and commonly will have an input and output endpoint for two-way communication. When you find the correct endpoint, open a UsbDeviceConnection on that endpoint. Supply the data that you want to transmit on the endpoint with the bulkTransfer() or controlTransfer() method. You should carry out this step in another thread to prevent blocking the main UI thread. The following code snippet is a trivial way to do a synchronous data transfer. Your code should have more logic to correctly find the correct interface and endpoints to communicate on and also should do any transferring of data in a different thread than the main UI thread: private Byte[] bytes private static int TIMEOUT = 0; private boolean forceClaim = true; ... UsbInterface intf = device.getInterface(0); UsbEndpoint endpoint = intf.getEndpoint(0); UsbDeviceConnection connection = mUsbManager.openDevice(device); connection.claimInterface(intf, forceClaim); connection.bulkTransfer(endpoint, bytes, bytes.length, TIMEOUT); //do in another thread To send data asynchronously, use the UsbRequest class to initialize and queue an asynchronous request, then wait for the result with requestWait().

Terminating

When you are done communicating with a device or if the device was detached, close the UsbInterface and UsbDeviceConnection by calling releaseInterface() and close(). To listen for detached events, create a broadcast receiver like below: BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {     public void onReceive(Context context, Intent intent) {         String action = intent.getAction();       if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {             UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);             if (device != null) {                 // call your method that cleans up and closes communication with the device             }         }     } }; Creating the broadcast receiver within the application, and not the manifest, allows your application to only handle detached events while it is running. This way, detached events are only sent to the application that is currently running and not broadcast to all applications.