三方库

implementation 'me.jahnen:libaums:0.7.6'

权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-feature android:name="android.hardware.usb.host" />

Note:Android 10 需要在Application标签中添加一条 android:requestLegacyExternalStorage="true" ,用于使用遗留存储权限,据说是因为安全原因。

帮助类

这里主要是用于读写图片的,如果只写文件就更简单了

/*** created by Taoyuan on 2020/10/26* USB帮助类*/
public class UsbUtils {private Context context;private UsbMassStorageDevice mDevice;private UsbFile cFolder;private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";// 文件目录public static String appDir = "App";public static String picDir = "picture";public boolean mUSBisOK = false;public UsbUtils(Context context) {this.context = context;init();}/*** 初始化广播,用于监听权限和插拔USB*/private void init() {// 权限广播BroadcastReceiver mUsbPermissionActionReceiver = new BroadcastReceiver() {public void onReceive(Context context, Intent intent) {String action = intent.getAction();if (ACTION_USB_PERMISSION.equals(action)) {context.unregisterReceiver(this);//解注册synchronized (this) {UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {if (usbDevice != null) {L.e(usbDevice.getDeviceName() + "已获取USB权限");//接收到U盘插入广播,尝试读取U盘设备数据mUSBisOK = readUsbList();//U盘已插入,并获取权限}} else {L.e("USB权限已被拒绝,Permission denied for device" + usbDevice);}}}}};context.registerReceiver(mUsbPermissionActionReceiver, new IntentFilter(ACTION_USB_PERMISSION));// otg插拔广播BroadcastReceiver mOtgReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction() == null) return;switch (intent.getAction()) {case UsbManager.ACTION_USB_DEVICE_ATTACHED://接收到U盘设备插入广播T.show(context, "U盘已插入");UsbDevice device_add = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);if (device_add != null) {//接收到U盘插入广播,尝试读取U盘设备数据mUSBisOK = readUsbList();//U盘已插入}break;case UsbManager.ACTION_USB_DEVICE_DETACHED://接收到U盘设设备拔出广播T.show(context, "U盘已拔出");mUSBisOK = readUsbList();//U盘已拔出break;}}};//监听otg插入 拔出IntentFilter usbDeviceStateFilter = new IntentFilter();usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);context.registerReceiver(mOtgReceiver, usbDeviceStateFilter);}/*** 读取U盘列表** @return 是否读取成功*/public boolean readUsbList() {boolean isOK = false;//设备管理器UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);//获取U盘存储设备UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(context);PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);//一般手机只有1个OTG插口for (UsbMassStorageDevice device : storageDevices) {//读取设备是否有权限if (usbManager == null) return false;if (usbManager.hasPermission(device.getUsbDevice())) {isOK = readDevice(device);} else {//没有权限,进行申请usbManager.requestPermission(device.getUsbDevice(), pendingIntent);}}if (storageDevices.length == 0) {T.show(context, "请插入可用的U盘");}return isOK;}/*** 读取设备(需已申请权限)** @param device usb设备* @return 是否读取成功*/private boolean readDevice(UsbMassStorageDevice device) {try {mDevice = device;mDevice.init();// 一般U盘只有一个分区,在android 10 实测时,只有FAT32可以被读取if (mDevice.getPartitions().size() == 0) {T.show(context, "读取设备分区失败");return false;} else {T.show(context, "U盘已就绪");FileSystem currentFs = mDevice.getPartitions().get(0).getFileSystem();cFolder = currentFs.getRootDirectory();return true;}} catch (IOException e) {e.printStackTrace();}return false;}/*** 向USB写数据** @param fileList 需要写入的文件* @return 是否写入成功*/public boolean write(List<File> fileList) {try {// 获取usb图片目录UsbFile[] usbFiles = cFolder.listFiles();UsbFile applicationDir = null;UsbFile pictureDir = null;// 判断目录是否存在,不存在则创建for (UsbFile usbFile : usbFiles) {if (usbFile.getName().equals(appDir)) {applicationDir = usbFile;}}// app目录不存在则创建if (applicationDir == null) {applicationDir = cFolder.createDirectory(appDir);} else {// 存在则遍历pic目录for (UsbFile usbFile : applicationDir.listFiles()) {if (usbFile.getName().equals(picDir)) {pictureDir = usbFile;}}}if (pictureDir == null) {pictureDir = applicationDir.createDirectory(picDir);}// 如果不存在则直接创建if (pictureDir.listFiles().length > 0) {// 如果存在,则先把重复文件从列表中清空一遍for (UsbFile usbFile : pictureDir.listFiles()) {for (int i = fileList.size() - 1; i >= 0; i--) {if (fileList.get(i).getName().equals(usbFile.getName())) {fileList.remove(i);}}}}if (fileList.size() == 0) {T.show(context, "选择文件已全部导出");return false;}List<UsbFile> usbFileList = new ArrayList<>();for (File file : fileList) {UsbFile file1 = pictureDir.createFile(file.getName());usbFileList.add(file1);}for (UsbFile usbFile : usbFileList) {for (int i = 0; i < fileList.size(); i++) {if (fileList.get(i).getName().equals(usbFile.getName())) {write2USB(fileList.get(i).getAbsolutePath(), usbFile);}}}mDevice.close();return true;} catch (IOException e) {e.printStackTrace();}return false;}/*** 写文件** @param source android设备中的文件路径* @param target usb目标文件*/public void write2USB(String source, UsbFile target) {try {BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));UsbFileOutputStream usbos = new UsbFileOutputStream(target);byte[] buffer = new byte[1024];int len = -1;while ((len = bis.read(buffer)) != -1) {usbos.write(buffer, 0, len);}bis.close();usbos.flush();usbos.close();} catch (java.io.FileNotFoundException e) {L.e("The File doesn't not exist.");} catch (IOException e) {e.printStackTrace();}}}

使用

UsbUtils usbUtils = new UsbUtils(this);
// 加载U盘
usbUtils.mUSBisOK = usbUtils.readUsbList();// 使用动态目录
if (!usbUtils.mUSBisOK) {T.show(this, "请先加载U盘");return;
}
UsbUtils.picDir = text;// 写文件
if (usbUtils.mUSBisOK) {List<File> fileList = new ArrayList<>();for (String imgPath : mData) {File file = FileUtils.getFileByPath(imgPath);if (file.exists()) fileList.add(file);}boolean writeOK = usbUtils.write(fileList);if (writeOK) T.show(this,"导出成功:" + UsbUtils.appDir + "/" + UsbUtils.picDir,true);
}

Android OTG U盘相关相关推荐

  1. android otg u盘 视频教程,Android OTG U盘文件读写

    最近要求对安卓平板开发时导出Excel表格到插在平板的U盘上,初步尝试发现,对U盘的文件读写只能操作Android/包名/的目录,不能直接写在根目录,不方便客户使用,于是研究了libaums的库可用是 ...

  2. Android OTG U盘文件读写

    Android U盘读写要用到的三方库:https://github.com/magnusja/libaums,使用方法地那就链接了解. 最近项目需要用到OTG功能,写了一个小demo,做为自己的笔记 ...

  3. android otg u盘 视频教程,手机u盘怎么用|OTG U盘正确使用教程

    当今社会,U盘的种类越来越多,今天小编想跟大家分享的是手机U盘.首先我们要弄清楚什么是"手机U盘". 手机U盘就是手机U盘,全称是智能手机USB闪存驱动器,简称智能U盘-V盘,英文 ...

  4. Android USB OTG U盘读写相关使用最全总结

    Android USB OTG U盘读写相关使用最全总结 https://blog.csdn.net/qq_29924041/article/details/80141514 androidOTG ( ...

  5. android M:第三方apk获取OTG(U盘)和sdcard路径

    Android M上,每次挂载OTG的时候,显示的设备是不一样的.这样子无法去判断挂载的设备的路径和区分sdcard与OTG(U盘). 网上查找了大量的文档,查看android源码,找到一个思路.做法 ...

  6. 高通android usb otg,Android OTG支持USB读卡器

    我们知道,三星Android手机将USB读卡器通过OTG线插入Micro USB插口后,插拔读卡器里的SD卡,文件管理器也能够识别卡的插拔:而很多手机的OTG连上USB读卡器也来插拔SD卡,会发现文件 ...

  7. linux/android驱动工程师面试相关内容总结

    理论的东西不常用时就会慢慢的被遗忘,但是找工作就是一个如何让别人相信自己的过程,理论知识就是一个非常重要的途径. 一次次机会在错失,每次想找工作时,刷一下简历就去面试了,一次次因为理论被鄙视,也该长长 ...

  8. Android 双u盘方案

     1      L1813系统上双U盘设计方案--系统设计 1.1     方案背景 Android原生的磁盘管理方案,设计的思想是将EMMC上的空间通过sdcard的server模拟成一个Sto ...

  9. Android OTG (USB Hos) 编程

    前言:最近在做一个汽车发动机故障检测的项目,负责APP开发.汽车发动机将各种数据通过OTG传输到Android手机,APP可以实时显示数据. 一.权限 1. 声明支持USB Hos模式 在Androi ...

  10. Android面试:Java相关

    Android面试常见Java相关问题. 原文链接:http://www.nowcoder.com/discuss/3244 Switch能否用string做参数? 在 Java 7 之前, swit ...

最新文章

  1. linux 魔兽 qq
  2. 「android」查看应用占用cpu和内存消耗情况
  3. 笔记-项目管理基础知识-项目组织结构
  4. 2017网易有道内推编程题
  5. 都快下班了,才来写日记
  6. 那年学过的Oracle笔记
  7. Word中批量删除引用符号
  8. android 天气动态壁纸,动态桌面壁纸 安卓“墨迹天气”新版评测
  9. 三、单因素方差分析例题(R语言)
  10. 12306 外包给阿里巴巴、IBM 等大企业做是否可行?
  11. MMD->Unity一站式解决方案
  12. 20145325张梓靖 《信息安全系统设计基础》第2周学习总结
  13. 公积金查询,公积金账号查询
  14. 6-ipv6基础知识之-有状态和无状态自动配置
  15. slam优化库,优化方法,G2o Ceres的学习
  16. java中year与week year
  17. 2022氟化工艺考试试题及答案
  18. NTLK1 :简单文本分析
  19. project子项目之间任务关联_任务关联的类型(Project)
  20. openfoam v8 波浪算例学习日记: 3.手动运行算例

热门文章

  1. 如何用计算机设计动画,用电脑制作3D动画的详细过程是怎样的?
  2. 投毒后门防御阅读笔记,What Doesn‘t Kill You Makes You Robust (er) Adversarial Training against Poisons and Back
  3. MySQL~高级应用 + 优化。
  4. 如何使用Zend Expressive建立NASA照片库
  5. 类与对象的基本语法+练习题
  6. FATAL: the database system is in recovery mode解决一例
  7. uniapp 动态设置导航栏标题 副标题 背景图片 web-view
  8. 【学习笔记】Stern-Brocot Tree
  9. 使用Yomail的时候出现的错误解决方案
  10. 超长攻略,机器学习基石!带你涉足王者之巅