How to detect attached USB device with UsbManager?

14,514

You probably want to look at the return code for registerReceiver - from what you are posting in your code I'd assume it would be failing since you don't actually instantiate your mUsbReceiver. Take a look at this code, which is from extracted from an application I've written that works, notice the difference in the way I'm setting up my BroadcastReceiver, this also shows how to request permission if your device is inserted:

PendingIntent mPermissionIntent = null; 
UsbManager mUsbManager = null;

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        if (ACTION_USB_PERMISSION.equals(action)) {
            // Permission requested
            synchronized (this) {
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    // User has granted permission
                    // ... Setup your UsbDeviceConnection via mUsbManager.openDevice(usbDevice) ...
                } else {
                    // User has denied permission
                }
            }
        }
        if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            // Device removed
            synchronized (this) {
                // ... Check to see if usbDevice is yours and cleanup ...
            }
        }
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            // Device attached
            synchronized (this) {
                // Qualify the new device to suit your needs and request permission
                if ((usbDevice.getVendorId() == MY_VID) && (usbDevice.getProductId() == MY_PID)) {
                    mUsbManager.requestPermission(usbDevice, mPermissionIntent);
                }
            }
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    // ... App Specific Setup Here ...

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

    // Register an intent filter so we can get permission to connect
    // to the device and get device attached/removed messages
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    registerReceiver(mUsbReceiver, filter);

    // ... More App Specific Setup ...
}

Also - it appears that for my app I did not need the extra intent-filter or meta-data XML for the USB actions.

Share:
14,514
Admin
Author by

Admin

Updated on June 22, 2022

Comments

  • Admin
    Admin almost 2 years

    I am new to android programming, my main aim is to communicate over USB to an MCU using FT200XD USB to I2C bridge.

    First I am trying to detect attached USB device via the UsbManager. From what I understand, at on create a popup window should ask permission to connect from the user but no permission is asked. While debugging its clear that the control doesn't go into the broadcast receiver section.

    I have refereed few example code snippet and wrote the code below. I don't know what I am doing wrong.

    I have downloaded an app called"USB host Controller" which does detect the FT200XD. Which means my tablet has the USB host functionality. It will be great if you can point me to the right direction or an entire working code can be shared.

    My code is as follows:

    Java file:

         @Override
        protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
    
           setContentView(R.layout.activity_fullscreen);
    
    
            mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    
            mPermissionIntent= PendingIntent.getBroadcast(this, 0, new  Intent(ACTION_USB_PERMISSION), 0); 
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            filter.addAction(UsbManager.EXTRA_PERMISSION_GRANTED);
            filter.addAction(ACTION_USB_PERMISSION);
            registerReceiver(mUsbReceiver, filter);
    
            }
    
    
    
     // Broadcast receiver
    
            public class  mUsbReceiver extends BroadcastReceiver { 
    
                public void onReceive(Context context, Intent intent) {
    
    
                    Toast.makeText(getApplicationContext(), 
                      "Inside USB Broadcast", Toast.LENGTH_SHORT).show();
    
                }
            }
    

    Manifest file part:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.usb"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="12"
            android:targetSdkVersion="19" />
    
         <uses-feature android:name="android.hardware.usb.host" />
    
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
    
             <receiver android:name="mUsbReceiver">
    
               <intent-filter>
                 <action android:name="android.hardware.usb.action.ACTION_USB_PERMISSION"/>
    
                </intent-filter>
             </receiver>
    
            <activity
                android:name="com.example.usb.FullscreenActivity"
                android:configChanges="orientation|keyboardHidden|screenSize"
                android:label="@string/app_name"
                android:theme="@style/FullscreenTheme" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
    
                 <intent-filter>
                    <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
                    <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/device_filter" />
    
    
            </activity>
        </application>
    
    </manifest>
    

    Device_filter.xml file:

        <?xml version="1.0" encoding="utf-8"?>
         <resources>
        <!-- 0x0403 / 0x6001: FTDI FT232R UART -->
        <usb-device vendor-id="1027" product-id="24577" />
    
        <!-- 0x2341 / Arduino -->
        <usb-device vendor-id="9025" />
    
        <!-- 0x16C0 / 0x0483: Teensyduino  -->
        <usb-device vendor-id="5824" product-id="1155" />
    
        <!-- 0x617 / 0x000b: EFPL CC2531 -->
        <usb-device vendor-id="1559" product-id="11" />
    
        <!-- vendor-id="0x0403" product-id="0x6015" // converted to Int vendor ID and product ID of my FT200XD-->
         <usb-device vendor-id="1027" product-id="24597" />
    
    </resources>