Android:从 Intent 接收 UsbDevice

标签 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");}

这是我的 list :

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

最佳答案

当您的应用程序由于 USB 设备附加事件而(重新)启动时,设备将在调用 onResume 时传递给 Intent。您可以使用 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());

关于Android:从 Intent 接收 UsbDevice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17828869/

相关文章:

android - 在相对布局中看不到编辑文本(屏幕外)

android - Alpha 动画不工作

android - 如何在按下后停止 android Mx Player

go - 在 Go 中使用 USB

linux - 查找带有 USB 设备 VID/PID 的/dev 条目

Android 平板电脑应用程序从 usb 发送接收数据

Android - 如何接收广播 Intent ACTION_SCREEN_ON/OFF?

java.net.UnknowHostException 与 ksoap2

android - FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY 未在 Nexus 10 (Android 4.4.2) 中设置

android - 设置根据 Intent Extras 值选择的微调项