java - 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()
调用中)
一旦我将其物理移除并重新插入,它就可以工作
有没有办法以编程方式“重新连接”设备,或者其他一些修复?谢谢
解决方案
检查应用程序启动时设备列表中是否存在设备。
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) {
}
}
推荐阅读
- c# - 具有 azure 函数和 Web api 的 EF Core 连接字符串设置
- google-sheets - 如何从谷歌表格中获取独特的未知单词列表
- r - 用于数据库连接的 R 函数装饰器
- amazon-eks - 连接到 AWS 上的 kubernetes 仅在通过 eksctl 创建集群时有效
- sql-server - 有条件地在脚本文件中设置 SQLCMD 变量?
- ios - NSArray 元素未能匹配 Swift Array 元素类型 Expected NSMutableArray 但找到 __NSDictionaryI:
- r - 如何将单元格元素转换为列
- c# - SQLite 的 MissingMethodException
- class - Flutter 类继承
- kubernetes - 任何知道如何从 kubernetes 命名空间中删除秘密的方法