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文件相关推荐
- iphone检测耳机插入/拔出
iphone检测耳机插入/拔出 开发过程中录音和播放这块碰到了一些问题,麻烦的主要有三个: 检测是否有声音输入设备 当有多个声音输出设备时,指定声音输出设备 检测耳机的插入和拔出 第一个问题,对于iT ...
- [iOS] iphone检测耳机插入/拔出
开发过程中录音和播放这块碰到了一些问题,麻烦的主要有三个: 检测是否有声音输入设备 当有多个声音输出设备时,指定声音输出设备 检测耳机的插入和拔出 第一个问题,对于iTouch和iPad等本身不带麦克 ...
- IOS成长之路-检测耳机插入/拔出
导入苹果的两个框架是必不可少的环节... 代码部分+小解: [cpp] view plaincopy - (void)viewDidLoad { [super viewDidLoad]; // Do ...
- 监听U盘插入 拔出 消息,获得U盘盘符
目录 一.U盘插拔消息监听 1.顶层窗口监听WM_DEVICECHANGE消息 2.WM_DEVICECHANGE 详细参数描述
- 在.NET中探测U盘的插入/拔出
当设备被插入/拔出的时候,WINDOWS会向每个窗体发送WM_DEVICECHANGE 消息,当消息的wParam 值等于 DBT_DEVICEARRIVAL 时,表示Media设备被插入并且已经可用 ...
- 断电的方法关闭计算机,win7设置usb关机断电|win7设置usb关机拔出断电的解决方法...
win7设置usb关机断电,win7设置usb关机拔出断电的解决方法?小伙伴们可能会经常性的遇到一个问题,就是win7电脑已经关闭了,但是插在计算机usb接口上的硬盘依然会被计算机供电,发出闪亮的光, ...
- Android APP 检测和监听当前USB设备插入拔出以及读取VID/PID
一.列出所有的usb device设备,打印vip pid private boolean AllDeviceConnected(){UsbManager manager = (UsbManager) ...
- linux udev 检测u盘的插入和拔出,在Linux中C检测插入/拔出USB串行设备
我需要检测何时在我的嵌入式系统上插入或拔出USB串行设备,并知道与之相关的tty是什么. 我的系统运行在2.6 Linux内核上. 由于我没有对udev规则的写访问权限,现在我正在尝试从文件系统获取此 ...
- Android实现检测耳机插入和拔出
在Android下实现检测耳机插入和拔出,也即建立一个Broadcast Receiver,监听"android.intent.action.HEADSET_PLUG"广播 但直接 ...
最新文章
- Tessellation (曲面细分) Displacement Mapping (贴图置换)
- Water Research:南土所褚海燕组揭示冰川源水体和沉积物细菌群落显著分异
- LeetCode Guess Number Higher or Lower II(动态规划)
- 遍历处理path及其子目录所有文件
- 这一年多来,阿里Blink测试体系如何从0走向成熟?
- Qt工作笔记-QGraphicsView框架容易忽视的坐标问题-“画布”QgraphicsScene到底放在了哪儿?
- windows下apache并发php,windows环境下apache死机问题的解决一例
- listview 不可滑动问题解决
- 大公司都有哪些开源项目~~~简化版
- 大数据安全分析需要关注哪些问题
- javascript紧接上一张for循环的问题,我自己的理解
- 优秀的CSS框架---bootstrap
- HRD 必须了解的持续绩效的优势
- Code Smell 检测工具调研
- 常见的域名劫持类型及如何修复
- here i am(歌手BryanAdams的歌曲)
- 第三部分:成交动力学之十大成交激素——9、紧迫感
- 搬砖的成长之路——VMWare网络原理
- 中文文本纠错算法走到多远了?
- 你深入解析过java虚拟机:C1编译器,从HIR到LIR吗?