Android P检测USB插入拔出消息并基于libaums实现读取USB文件

2024-02-22 00:58

本文主要是介绍Android P检测USB插入拔出消息并基于libaums实现读取USB文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Android设备中检测USB插入消息,并且从USB中读取文件。

一、导入libaums包

libaums开源项目地址:https://github.com/magnusja/libaums
build.gradle文件中引用libaums:
implementation 'com.github.mjdev:libaums:+’

或者编译出libaums-0.6.0.jar,导入jar包:
implementation files(‘libs/libaums-0.6.0.jar’)

二、新建一个广播,接收USB插入消息,并读取Usb文件

检测到Usb插入:UsbManager.ACTION_USB_DEVICE_ATTACHED;
检测到Usb拔出:UsbManager.ACTION_USB_DEVICE_DETACHED.
readUsbDeviceList()获取Usb设备请申请访问权限或者调用readDevice读取Usb文件;
readDevice()为读取Usb中文件操作;

//Usb中要读取的文件
private static final String MCU_VERSION_FILE = "version.txt";public class UsbIntentReceiver extends BroadcastReceiver {private static final String TAG = "UsbIntentReceiver";private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";//Usb listprivate static UsbMassStorageDevice[] mStorageDevices;//Usb pathprivate UsbFile mUsbPath;@Overridepublic void onReceive(Context context, Intent intent) {final UsbDevice device = intent.getExtras().getParcelable(UsbManager.EXTRA_DEVICE);switch (intent.getAction()) {case UsbManager.ACTION_USB_DEVICE_ATTACHED://检测到USB插入,读取Usb设备readUsbDeviceList(context);break;case UsbManager.ACTION_USB_DEVICE_DETACHED://检测到Usb拔出break;case ACTION_USB_PERMISSION://通知一个弹框,询问用户对Usb的访问权限,用户选择ok,表示可以访问Usb设备//申请对USB的读写权限//返回true,表示用户选择了ok,同意进行读取Usbif(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,false)){if(device != null ){//已经获取到Usb访问权限,读取设备readDevice(context,getUsbMass(device));}}break;}}private void readUsbDeviceList(Context context) {//获取当前Usb设备mStorageDevices = UsbMassStorageDevice.getMassStorageDevices(context);//打印当前有几个Usb设备Log.i(TAG,"sunxiaolin,readUsbDeviceList,mStorageDevices.length=" + mStorageDevices.length);//创建一个弹框类型ACTION_USB_PERMISSIONUsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);for (UsbMassStorageDevice device : mStorageDevices) {if (usbManager.hasPermission(device.getUsbDevice())) {//已经获取到Usb访问权限,直接读取设备readDevice(context, device);}else {//通知一个弹框,询问用户对Usb的访问权限,用户选择ok,表示可以访问Usb设备//没有访问权限,申请权限usbManager.requestPermission(device.getUsbDevice(), pendingIntent);}}}private UsbMassStorageDevice getUsbMass(UsbDevice usbDevice){Log.i(TAG,"sunxiaolin:getUsbMass,usbDevice=" + usbDevice);if( mStorageDevices != null && mStorageDevices.length > 0){for( UsbMassStorageDevice device : mStorageDevices){Log.i(TAG,"sunxiaolin:getUsbMass,device=" + device);if(usbDevice.equals(device.getUsbDevice())){return device;}}}return null;}private void readDevice(Context context, UsbMassStorageDevice device) {try {device.init();// Only uses the first partition on the devicePartition partion = device.getPartitions().get(0);Log.i(TAG,"sunxiaolin,partion=" + partion);FileSystem currentFs = partion.getFileSystem();//Toast.makeText(context, "getRootDirectory: " + currentFs.getRootDirectory().getName(), Toast.LENGTH_LONG).show();Log.d(TAG, "Capacity: " + currentFs.getCapacity());//Toast.makeText(context, "Capacity: " + currentFs.getCapacity(), Toast.LENGTH_LONG).show();Log.d(TAG, "Occupied Space: " + currentFs.getOccupiedSpace());//Toast.makeText(context, "Occupied Space: " + currentFs.getOccupiedSpace(), Toast.LENGTH_LONG).show();Log.d(TAG, "Free Space: " + currentFs.getFreeSpace());//Toast.makeText(context, "Free Space: " + currentFs.getFreeSpace(), Toast.LENGTH_LONG).show();Log.d(TAG, "Chunk size: " + currentFs.getChunkSize());//Toast.makeText(context, "Chunk size: " + currentFs.getChunkSize(), Toast.LENGTH_LONG).show();mUsbPath = currentFs.getRootDirectory();///< 读取当前目录下的文件readDataFromUsb(context);} catch (Exception e) {e.printStackTrace();}}private void readDataFromUsb(Context context) {UsbFile[] usbFiles = new UsbFile[0];try {usbFiles = mUsbPath.listFiles();} catch (IOException e) {e.printStackTrace();}if (null != usbFiles && usbFiles.length > 0) {for (UsbFile usbFile : usbFiles) {Log.i(TAG,"sunxiaolin,usbFile=" + usbFile);if (usbFile.getName().equals(VERSION_FILE)) {readTxtFromUsb(usbFile);Toast.makeText(context, "usbFile.getName(): " + usbFile.getName(), Toast.LENGTH_LONG).show();}}}}private void readTxtFromUsb(UsbFile usbFile) {UsbFile descFile = usbFile;//mMcuUpdateFile = usbFile;InputStream is = new UsbFileInputStream(descFile);StringBuilder sb = new StringBuilder();BufferedReader bufferedReader = null;try {bufferedReader = new BufferedReader(new InputStreamReader(is));String read;while ((read = bufferedReader.readLine()) != null) {sb.append(read);Log.i(TAG,"sunxiaolin,readTxtFromUDisk,readResult=" + read);}} catch (Exception e) {e.printStackTrace();} finally {try {if (bufferedReader != null) {bufferedReader.close();}} catch (IOException e) {e.printStackTrace();}}}
}
三、在AndroidManifest.xml中申请权限和配置广播
<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE/> 
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE/> <receiverandroid:name=".UsbIntentReceiver"android:exported="true"><intent-filter><action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /><action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" /><action android:name="com.android.example.USB_PERMISSION" /></intent-filter><meta-dataandroid:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"android:resource="@xml/device_filter" />
</receiver>

xml文件device_filter:

<resources><!-- filter for MTP/PTP devices --><usb-device class="255" subclass="255" protocol="0" /><usb-device class="6" subclass="1" protocol="1" />
</resources>

总结:其中有一个申请权限,弹出框然该用户选择允许访问usb设备,是安卓为了提高用户隐私采取的措施,提醒用户哪些权限被使用。如果去掉还是要在系统中去修改权限。

这篇关于Android P检测USB插入拔出消息并基于libaums实现读取USB文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/733642

相关文章

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删

SpringBoot整合mybatisPlus实现批量插入并获取ID详解

《SpringBoot整合mybatisPlus实现批量插入并获取ID详解》这篇文章主要为大家详细介绍了SpringBoot如何整合mybatisPlus实现批量插入并获取ID,文中的示例代码讲解详细... 目录【1】saveBATch(一万条数据总耗时:2478ms)【2】集合方式foreach(一万条数

使用Python实现矢量路径的压缩、解压与可视化

《使用Python实现矢量路径的压缩、解压与可视化》在图形设计和Web开发中,矢量路径数据的高效存储与传输至关重要,本文将通过一个Python示例,展示如何将复杂的矢量路径命令序列压缩为JSON格式,... 目录引言核心功能概述1. 路径命令解析2. 路径数据压缩3. 路径数据解压4. 可视化代码实现详解1

PyQt6/PySide6中QTableView类的实现

《PyQt6/PySide6中QTableView类的实现》本文主要介绍了PyQt6/PySide6中QTableView类的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学... 目录1. 基本概念2. 创建 QTableView 实例3. QTableView 的常用属性和方法

PyQt6/PySide6中QTreeView类的实现

《PyQt6/PySide6中QTreeView类的实现》QTreeView是PyQt6或PySide6库中用于显示分层数据的控件,本文主要介绍了PyQt6/PySide6中QTreeView类的实现... 目录1. 基本概念2. 创建 QTreeView 实例3. QTreeView 的常用属性和方法属性

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

pandas中位数填充空值的实现示例

《pandas中位数填充空值的实现示例》中位数填充是一种简单而有效的方法,用于填充数据集中缺失的值,本文就来介绍一下pandas中位数填充空值的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是中位数填充?为什么选择中位数填充?示例数据结果分析完整代码总结在数据分析和机器学习过程中,处理缺失数