You are here
Home > HelloWorld >

USB Communication


About Android USB

Android supports USB devices through two modes:

  • Android Accessory: In this mode external USB device acts as host.
  • Android Host: In this mode Android Device acts as host and powers the external device.

Manifest File for USB connection

We want to be notified when an external USB device is attached to the Android device.This can be done adding a new intent filter entry to the Activity that should be started by the system when a USB device is plugged in.

<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
<meta-data  android:name=
android:resource="@xml/device_filter" />    
<meta-data android:name=
android:resource="@xml/device_filter" />

In above code, MainActivity registers to be informed when a USB device is connected (USB_DEVICE_ATTACHED) or disconnected (USB_DEVICE_DETACHED). If we want to restrict the type of devices, we can include a device filter XML file indicated in the meta-data element.This file is stored in /res/xml folder and lists combinations of vendor id , product id ,manufacturer,version etc.

USB Configuration in java file

To receive the USB events, we need to create a BroadcastReceiver and then register it. In this case, the events will be received via the onReceive() method of BroadcastReceiver.

private static final String ACTION_USB_ATTACHED  = "android.hardware.usb.action.USB_DEVICE_ATTACHED";  
private static final String ACTION_USB_DETACHED  = "android.hardware.usb.action.USB_DEVICE_DETACHED"; 
BroadcastReceiver bReceiver= new BroadcastReceiver() {...};  
IntentFilter filter = new IntentFilter();  
public void onReceive(Context context, Intent intent) {  
String action = intent.getAction();          
if (action.equalsIgnoreCase(ACTION_USB_DETACHED)) {...}         ...


Before communicating with the USB accessory, your application must have permission from your users.If you want to obtain permission explicitly, then you need to call requestPermission(). In onCreate() you need to create permission intent and pass that to requestPermission().


Once permission granted openAccessory() method will be called.This method is used to communicate with accessory.file descriptor can be used to set up input and output streams to read and write data to descriptor.The streams represent the accessory’s input and output endpoints.