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文件相关推荐

  1. iphone检测耳机插入/拔出

    iphone检测耳机插入/拔出 开发过程中录音和播放这块碰到了一些问题,麻烦的主要有三个: 检测是否有声音输入设备 当有多个声音输出设备时,指定声音输出设备 检测耳机的插入和拔出 第一个问题,对于iT ...

  2. [iOS] iphone检测耳机插入/拔出

    开发过程中录音和播放这块碰到了一些问题,麻烦的主要有三个: 检测是否有声音输入设备 当有多个声音输出设备时,指定声音输出设备 检测耳机的插入和拔出 第一个问题,对于iTouch和iPad等本身不带麦克 ...

  3. IOS成长之路-检测耳机插入/拔出

    导入苹果的两个框架是必不可少的环节... 代码部分+小解: [cpp] view plaincopy - (void)viewDidLoad { [super viewDidLoad]; // Do  ...

  4. 监听U盘插入 拔出 消息,获得U盘盘符

    目录 一.U盘插拔消息监听 1.顶层窗口监听WM_DEVICECHANGE消息 2.WM_DEVICECHANGE 详细参数描述

  5. 在.NET中探测U盘的插入/拔出

    当设备被插入/拔出的时候,WINDOWS会向每个窗体发送WM_DEVICECHANGE 消息,当消息的wParam 值等于 DBT_DEVICEARRIVAL 时,表示Media设备被插入并且已经可用 ...

  6. 断电的方法关闭计算机,win7设置usb关机断电|win7设置usb关机拔出断电的解决方法...

    win7设置usb关机断电,win7设置usb关机拔出断电的解决方法?小伙伴们可能会经常性的遇到一个问题,就是win7电脑已经关闭了,但是插在计算机usb接口上的硬盘依然会被计算机供电,发出闪亮的光, ...

  7. Android APP 检测和监听当前USB设备插入拔出以及读取VID/PID

    一.列出所有的usb device设备,打印vip pid private boolean AllDeviceConnected(){UsbManager manager = (UsbManager) ...

  8. linux udev 检测u盘的插入和拔出,在Linux中C检测插入/拔出USB串行设备

    我需要检测何时在我的嵌入式系统上插入或拔出USB串行设备,并知道与之相关的tty是什么. 我的系统运行在2.6 Linux内核上. 由于我没有对udev规则的写访问权限,现在我正在尝试从文件系统获取此 ...

  9. Android实现检测耳机插入和拔出

    在Android下实现检测耳机插入和拔出,也即建立一个Broadcast Receiver,监听"android.intent.action.HEADSET_PLUG"广播 但直接 ...

最新文章

  1. python入门指南许半仙txt-影帝的脑子坏了 第23章
  2. 为什么企业需关心DDoS攻击?—Vecloud微云
  3. B样条数据点反求控制点绘制曲线(源码)
  4. tarjan算法_【朝夕的ACM笔记】树上问题-最近公共祖先-倍增算法
  5. Windows命令行参数的知识(一)
  6. POJ2886线段树 Joseph游戏(单点更新)
  7. Spark读取文本文件并转换为DataFrame
  8. python群发短信脚本_python实现zabbix发送短信脚本
  9. C语言各种类型数据的输出显示
  10. 树状数组(区间,单点间操作)
  11. 博途 V14安装教程
  12. 作为一名管理者,如何做好上传下达工作呢?
  13. eclipse插件开发:把自定义的文件类型使用xml编辑器打开
  14. codewars题目解答Multiples of 3 or 5
  15. 华大HC32L130 SPI和GPIO模拟驱动NF-03和NF-01-s模块(SI24R1方案,兼容NRF24L01)
  16. 海思AI芯片(Hi35XX): 图像jpg转.bgr
  17. 杭州市拥北发展是否是最优解,拥江发展处于何种地位
  18. capl保存trace_CANoe常用操作(CANoe系列其一)
  19. 简易磁盘写入速度测试工具(GO)
  20. 软件工程与计算II-19-软件测试

热门文章

  1. PAT乙级刷题记录——1046 划拳 (15分)
  2. 小心!显卡BIOS刷新工具Nvflash变杀手
  3. C语言 — 必学的编程基础语法,入门就从这里开始!
  4. Python学习系列 -- 改善 Python 程序的 91 个建议
  5. 计算机材料仿真,材料微结构的计算机仿真
  6. 爬取免费代理IP并测试
  7. superset启动脚本及安装
  8. 机器学习-白板推导系列笔记(三十四)-MDP
  9. 查看linux重启机时间,【linux】查看Linux开机时间/重启时间/运行时间
  10. MATLAB绘制 “甲基橙“分子示例图(整活)