Android:从意图接收UsbDevice

时间:2013-07-24 08:33:13

标签: android android-intent usb

我正在搞乱USB主机,并遵循指南on the Android Developers网站我设法创建一个Hello World,一旦插入特定的USB设备就启动。但是,当我尝试和“...从intent中获取代表附加设备的UsbDevice”它返回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");}

这是我的清单:

<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>

我的xml / device_filter.xml(我知道这些是正确的VID和PID,因为我有一个类似的应用使用描述on the Android Developers网站的枚举方法):

<resources>
    <usb-device vendor-id="1234" product-id="1234"/>
</resources>

2 个答案:

答案 0 :(得分:5)

当您的应用程序由于USB设备附加事件而(重新)启动时,设备会在调用onResume时传递给意图。您可以使用getParcelableExtra方法进行操作。例如:

@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());

答案 1 :(得分:1)

由于Taylor Alexander,我找到了解决方法(或预期用途?)。基本上,我理解它的方式是触发打开应用程序的意图只打开应用程序。之后,您必须根据onResume方法中Android Developers页面的Enumerating Devices部分搜索并访问USB设备。

@Override
    public void onResume() {
        super.onResume();

        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

        while(deviceIterator.hasNext()){
            UsbDevice device = deviceIterator.next();
                // Your code here!
        }

我不相信这是做这件事的正确方法,但似乎有效。如果有人有任何进一步的建议,我会很高兴听。