首页 > 解决方案 > USB 设备在打开应用程序后重新连接后才能使用

问题描述

因此,为了缓解每次启动应用程序时都必须授予权限的问题,我遵循了这个答案

所以我有我的设备过滤器设置

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

清单中的活动

    <activity
        android:name=".demo.Activity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/title_demo"
        android:theme="@style/FullscreenTheme">
        <intent-filter>
            <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/usb_device_filter" />
    </activity>

然后在我的java文件中

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action))
        {
            synchronized (this)
            {
                UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if(device != null)
                {
                   checkDevice();
                }
            }
        }
    }
};
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
mContext.registerReceiver(mUsbReceiver, filter);

如果我在连接设备的情况下启动应用程序,它不会亮起,并且设备的 API 不会与它通信(但是它确实显示在UsbManager.getDeviceList()调用中)

一旦我将其物理移除并重新插入,它就可以工作

有没有办法以编程方式“重新连接”设备,或者其他一些修复?谢谢

标签: javaandroid

解决方案


检查应用程序启动时设备列表中是否存在设备。

UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
Iterator devices = manager.getDeviceList().entrySet().iterator();
while (devices.hasNext()) {
    Map.Entry pair = (Map.Entry) devices.next();
    Log.i(TAG, pair.getKey() + " = " + pair.getValue());

    UsbDevice device = (UsbDevice) pair.getValue();
    Log.i(TAG, "UsbDevice: " + device.toString());
    if(device.getVendorId() == 1234 && device.getProductId() == 5678) {

    }
}

推荐阅读