Android:从意图接收UsbDevice

zot*_*tty 5 usb android android-intent

我正在搞乱USB主机,并遵循Android开发者网站的指导原则,我设法创建了一个Hello World,一旦插入特定的USB设备就会启动.但是,当我尝试"...时...从意图"它返回null"获取表示附加设备的UsbDevice:

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");}
Run Code Online (Sandbox Code Playgroud)

这是我的清单:

<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>
Run Code Online (Sandbox Code Playgroud)

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

<resources>
    <usb-device vendor-id="1234" product-id="1234"/>
</resources>
Run Code Online (Sandbox Code Playgroud)

小智 6

当您的应用程序由于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());
Run Code Online (Sandbox Code Playgroud)


zot*_*tty 2

感谢Taylor Alexander,我找到了一个解决方法(或预期用途?) 。基本上,我的理解是,触发打开应用程序的意图只会打开应用程序。之后,您必须按照onResume 方法中 Android 开发人员页面的 枚举设备部分搜索并访问 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!
        }
Run Code Online (Sandbox Code Playgroud)

我不相信这是正确的方法,但它似乎有效。如果有人有任何进一步的建议,我很乐意倾听。