Android 获得 usb 权限的两种方式

news/2024/10/18 19:26:37/

0. 前言

在做 USB OTG 通信时,第一步就是要能够获取到 usb 的使用权限,因此特地在此处介绍一下两种我用过的获取 usb 权限方式。

1. 直接在 AndroidManifest.xml 中配置

这种配置方式是在 github 上 usb-serial-for-android 项目中看到的,大家如果有兴趣可以 clone 下来研究一下。

<activity
            android:name=".DeviceListActivity"android:label="@string/app_name"android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"><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/device_filter" /></activity>

其中 device_filter.xml 中列出了可用 usb 设备,当usb 设备连接手机之后,app 会自动询问是否允许获取该 usb 的权限。
device_filter.xml 放置位置如下图所示
这里写图片描述
内容为

<?xml version="1.0" encoding="utf-8"?>
<resources><!-- 0x0403 / 0x6001: FTDI FT232R UART --><usb-device vendor-id="1027" product-id="24577" /><!-- 0x0403 / 0x6015: FTDI FT231X --><usb-device vendor-id="1027" product-id="24597" /><!-- 0x2341 / Arduino --><usb-device vendor-id="9025" /><!-- 0x16C0 / 0x0483: Teensyduino  --><usb-device vendor-id="5824" product-id="1155" /><!-- 0x10C4 / 0xEA60: CP210x UART Bridge --><usb-device vendor-id="4292" product-id="60000" /><!-- 0x067B / 0x2303: Prolific PL2303 --><usb-device vendor-id="1659" product-id="8963" /><!-- 0x1a86 / 0x7523: Qinheng CH340 --><usb-device vendor-id="6790" product-id="29987" />
</resources>

每个 usb 设备通过 vendor-id(厂商 id) 和 product-id (产品 id)一起来定义的,这里有一个 linux 的 usb设备厂商 id 和产品 id 的汇总,可以作为 Android usb 设备的参考。

2. 在代码中获取

这代码是在其他博客中看到的,忘记是哪篇了,这里就不引用了。直接上代码。

/*** 获得 usb 权限*/private void openUsbDevice(){//before open usb device//should try to get usb permissiontryGetUsbPermission();}UsbManager mUsbManager;private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";private void tryGetUsbPermission(){mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);registerReceiver(mUsbPermissionActionReceiver, filter);PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);//here do emulation to ask all connected usb device for permissionfor (final UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {//add some conditional check if necessary//if(isWeCaredUsbDevice(usbDevice)){if(mUsbManager.hasPermission(usbDevice)){//if has already got permission, just goto connect it//that means: user has choose yes for your previously popup window asking for grant perssion for this usb device//and also choose option: not ask againafterGetUsbPermission(usbDevice);}else{//this line will let android popup window, ask user whether to allow this app to have permission to operate this usb devicemUsbManager.requestPermission(usbDevice, mPermissionIntent);}//}}}private void afterGetUsbPermission(UsbDevice usbDevice){//call method to set up device communication//Toast.makeText(this, String.valueOf("Got permission for usb device: " + usbDevice), Toast.LENGTH_LONG).show();//Toast.makeText(this, String.valueOf("Found USB device: VID=" + usbDevice.getVendorId() + " PID=" + usbDevice.getProductId()), Toast.LENGTH_LONG).show();doYourOpenUsbDevice(usbDevice);}private void doYourOpenUsbDevice(UsbDevice usbDevice){//now follow line will NOT show: User has not given permission to device UsbDeviceUsbDeviceConnection connection = mUsbManager.openDevice(usbDevice);//add your operation code here}private final BroadcastReceiver mUsbPermissionActionReceiver = new BroadcastReceiver() {public void onReceive(Context context, Intent intent) {String action = intent.getAction();if (ACTION_USB_PERMISSION.equals(action)) {synchronized (this) {UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {//user choose YES for your previously popup window asking for grant perssion for this usb deviceif(null != usbDevice){afterGetUsbPermission(usbDevice);}}else {//user choose NO for your previously popup window asking for grant perssion for this usb deviceToast.makeText(context, String.valueOf("Permission denied for device" + usbDevice), Toast.LENGTH_LONG).show();}}}}};

http://www.ppmy.cn/news/182541.html

相关文章

tcp服务器异常情况

服务器提供回射服务&#xff08;将客户端发送的内容回送到客户端上&#xff09; 1. 服务器没有开启回射服务 客户端启动tcpcli &#xff0c; 调用connect连接 那么在str_cli 里面的 一write socket 就会产生SIGPIPE这是因为connect连接服务器 服务器产生RST&#xff0c; 当向一…

LeNet-5-实现-cifar2

标题#LeNet-5 完成 cifar2&#xff08;无注释源代码在本文最下方&#xff09; import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.keras import layers, losses, Model 1)定义一个有参有返回值的函数用于加载图片 def load_img(file_path): img tf…

gearman mysql_gearman的持久化,以mysql的方式

1、为什么要持久化? gearman的job server中的工作队列存储在内存中&#xff0c;一旦服务器有未处理的任务时重启或者宕机&#xff0c;那么这些任务就会丢失。 持久化存储队列可以允许添加后台任务&#xff0c;并将其存储在外部的持久型队列里(比如MySQL数据库)。 2、关于gearm…

2021-05-18文件的读取和写入

文件的读取与字典 # file1 open(d:\note1.txt)#注意转义符 # file1 open(d:\\note1.txt)#多写一个\ # file1 open(d:/note1.txt)#用/代替\ # file1 open(rd:\note1.txt)#前面加一个r # file1open(d:/ceshi.txt,r) #r读取模式&#xff0c;w写入模式&#xff08;会清空之前的内容…

Appium日志分析

Appium工作期间每个端口号的作用&#xff1a; 4723 &#xff1a;Appium服务的端口&#xff0c;负责接收脚本端发送过来的请求 4724&#xff1a;手机设备上的Bootstrap 端口&#xff0c;监听服务端 8200&#xff1a;Appium服务的端口&#xff0c;负责跟手机端进行交互 6790&…

Codeforces Round #790 (Div. 4)(A-E 题解)

Codeforces Round #790 A-E 题解 A. Lucky?B. Equal CandiesC. Most Similar WordsD. X-SumE. Eating Queries A. Lucky? A. Lucky? 题意 给你 t 个六位数&#xff08;可能含前导0&#xff09;&#xff0c;对于每个六位数&#xff0c;如果前三位数字之和等于后三位数字之和…

php内核函数手册,开扒php内核函数,第三篇 implode

一开始觉得implode挺容易实现&#xff0c;但是写着写着才发现是挺复杂的&#xff0c;不说啦 来看看implode的用法吧 1 ? php 2 $arr array (Hello,World!,Beautiful,Day! ); 3 echo implode (" ", $arr ); 4 ? 上面会输出 Hello World! Beautiful Day! 下面的程序…

Appium运行时日志解析(内附Demo)

[Appium] Welcome to Appium v1.15.1 启动Appium1.15.1版本 [Appium] Non-default server args: [Appium] allowInsecure: { [Appium] } [Appium] denyInsecure: { [Appium] } [Appium] Appium REST http interface listener started on 0.0.0.0:4723 监听4723端口 [HTTP] --&g…