Android OTG U盘相关

三方库

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() {
            @Override
            public 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);
}