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);
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268