Android: Receive UsbDevice from intent
android, android-intent, usb
Solution
When your application is (re-)started due to the USB device attach event, then the device is passed on to the intent when `onResume` is called. You can get to it using the `getParcelableExtra` method. For example:
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
if (intent != null) {
Log.d("onResume", "intent: " + intent.toString());
if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (usbDevice != null) {
Log.d("onResume", "USB device attached: name: " + usbDevice.getDeviceName());
Problem
I'm messing about with the USB host, and following the guidelines on the Android Developers site I've managed to create a Hello World that starts up once a particular USB device is plugged in. However, when I try and "...obtain the UsbDevice that represents the attached device from the intent" it returns null: ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(); UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); // device is always null if (device == null){Log.i(TAG,"Null device");} ``` Here's my manifest: ``` <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" /> </activity> </application> ``` And my xml/device_filter.xml (I know these are the correct VID and PID because I've got a similar app working using the enumeration method described on the Android Developers site): ``` <resources> <usb-device vendor-id="1234" product-id="1234"/> </resources> ```