Android-USB-OTG-讀寫U盤文件

參考:
https://developer.android.com/guide/topics/connectivity/usb/host.html
https://blog.csdn.net/qq_29924041/article/details/80141514

本文介紹Android手機通過OTG數(shù)據(jù)線讀寫USB存儲設備(U盤,移動硬盤,存儲卡)的兩種方法

方法一: 直接和USB設備建立連接,借助第三方庫libaums識別U盤的文件系統(tǒng)

由于libaums只支持FAT32文件系統(tǒng),所以U盤的格式化必須采用FAT32!
該庫的GitHub地址: https://github.com/magnusja/libaums

1.權(quán)限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
// 手機必須支持USB主機特性(OTG)
<uses-feature android:name="android.hardware.usb.host" />

2.監(jiān)聽USB插入/拔出

private static final String ACTION_USB_PERMISSION = "com.demo.otgusb.USB_PERMISSION";
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;    
private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: " + intent);
        String action = intent.getAction();
        if (action == null)
            return;
        switch (action) {
            case ACTION_USB_PERMISSION://用戶授權(quán)廣播
                synchronized (this) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { //允許權(quán)限申請
                        test();
                    } else {
                        logShow("用戶未授權(quán),訪問USB設備失敗");
                    }
                }
                break;
            case UsbManager.ACTION_USB_DEVICE_ATTACHED://USB設備插入廣播
                logShow("USB設備插入");
                break;
            case UsbManager.ACTION_USB_DEVICE_DETACHED://USB設備拔出廣播
                logShow("USB設備拔出");
                break;
        }
    }
};

private void init() {   
    //USB管理器
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
    
    //注冊廣播,監(jiān)聽USB插入和拔出
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    intentFilter.addAction(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, intentFilter);

    //讀寫權(quán)限
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE}, 111);
    }
}

3.使用libaums庫讀寫U盤文件

private void test() {
    try {
        UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
        for (UsbMassStorageDevice storageDevice : storageDevices) { //一般手機只有一個USB設備
            // 申請USB權(quán)限
            if (!mUsbManager.hasPermission(storageDevice.getUsbDevice())) {
                mUsbManager.requestPermission(storageDevice.getUsbDevice(), mPermissionIntent);
                break;
            }
            // 初始化
            storageDevice.init();
            // 獲取分區(qū)
            List<Partition> partitions = storageDevice.getPartitions();
            if (partitions.size() == 0) {
                logShow("錯誤: 讀取分區(qū)失敗");
                return;
            }
            // 僅使用第一分區(qū)
            FileSystem fileSystem = partitions.get(0).getFileSystem();
            logShow("Volume Label: " + fileSystem.getVolumeLabel());
            logShow("Capacity: " + fSize(fileSystem.getCapacity()));
            logShow("Occupied Space: " + fSize(fileSystem.getOccupiedSpace()));
            logShow("Free Space: " + fSize(fileSystem.getFreeSpace()));
            logShow("Chunk size: " + fSize(fileSystem.getChunkSize()));

            UsbFile root = fileSystem.getRootDirectory();
            UsbFile[] files = root.listFiles();
            for (UsbFile file : files)
                logShow("文件: " + file.getName());

            // 新建文件
            UsbFile newFile = root.createFile("hello_" + System.currentTimeMillis() + ".txt");
            logShow("新建文件: " + newFile.getName());

            // 寫文件
            // OutputStream os = new UsbFileOutputStream(newFile);
            OutputStream os = UsbFileStreamFactory.createBufferedOutputStream(newFile, fileSystem);
            os.write(("hi_" + System.currentTimeMillis()).getBytes());
            os.close();
            logShow("寫文件: " + newFile.getName());

            // 讀文件
            // InputStream is = new UsbFileInputStream(newFile);
            InputStream is = UsbFileStreamFactory.createBufferedInputStream(newFile, fileSystem);
            byte[] buffer = new byte[fileSystem.getChunkSize()];
            int len;
            File sdFile = new File("/sdcard/111");
            sdFile.mkdirs();
            FileOutputStream sdOut = new FileOutputStream(sdFile.getAbsolutePath() + "/" + newFile.getName());
            while ((len = is.read(buffer)) != -1) {
                sdOut.write(buffer, 0, len);
            }
            is.close();
            sdOut.close();
            logShow("讀文件: " + newFile.getName() + " ->復制到/sdcard/111/");

            storageDevice.close();
        }
    } catch (Exception e) {
        logShow("錯誤: " + e);
    }
}

public static String fSize(long sizeInByte) {
    if (sizeInByte < 1024)
        return String.format("%s", sizeInByte);
    else if (sizeInByte < 1024 * 1024)
        return String.format(Locale.CANADA, "%.2fKB", sizeInByte / 1024.);
    else if (sizeInByte < 1024 * 1024 * 1024)
        return String.format(Locale.CANADA, "%.2fMB", sizeInByte / 1024. / 1024);
    else
        return String.format(Locale.CANADA, "%.2fGB", sizeInByte / 1024. / 1024 / 1024);
}

方法二: 獲取U盤的掛載路徑,直接讀寫U盤(就像掛載sdcard讀寫文件)

對于U盤的文件系統(tǒng),只依賴于手機系統(tǒng)是否支持,無需我們做額外工作(所有Android手機都支持FAT32,有個別手機還支持NTFS)
但是有些手機無法獲取掛載路徑(如小米等,就算通過mount命令找到掛載路徑也沒有權(quán)限讀寫),所以該方法通用性其實不如方法一!

1.通過MEDIA廣播獲取掛載路徑

// 注冊系統(tǒng)廣播
<receiver android:name=".MediaReceiver">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_CHECKING" />
        <action android:name="android.intent.action.MEDIA_MOUNTED" />
        <action android:name="android.intent.action.MEDIA_EJECT" />
        <action android:name="android.intent.action.MEDIA_UNMOUNTED" />

        <data android:scheme="file" />
    </intent-filter>
</receiver>

// 獲取USB掛載路徑
public class MediaReceiver extends BroadcastReceiver {      
    @Override
    public void onReceive(Context context, Intent intent) {
        switch (intent.getAction()) {
            case Intent.ACTION_MEDIA_CHECKING:
                break;
            case Intent.ACTION_MEDIA_MOUNTED:
                // 獲取掛載路徑, 讀取U盤文件
                Uri uri = intent.getData();
                if (uri != null) {
                    String filePath = uri.getPath();
                    File rootFile = new File(filePath);
                    for (File file : rootFile.listFiles()) {
                        // 文件列表...
                    }
                }
                break;
            case Intent.ACTION_MEDIA_EJECT:
                break;
            case Intent.ACTION_MEDIA_UNMOUNTED:
                break;
        }
    }
}

2.通過反射系統(tǒng)方法獲取掛載路徑

public static List<String> getUsbPaths(Context cxt) {
    List<String> usbPaths = new ArrayList<>();
    try {
        StorageManager srgMgr = (StorageManager) cxt.getSystemService(Context.STORAGE_SERVICE);
        Class<StorageManager> srgMgrClass = StorageManager.class;
        String[] paths = (String[]) srgMgrClass.getMethod("getVolumePaths").invoke(srgMgr);
        for (String path : paths) {
            Object volumeState = srgMgrClass.getMethod("getVolumeState", String.class).invoke(srgMgr, path);
            if (!path.contains("emulated") && Environment.MEDIA_MOUNTED.equals(volumeState))
                usbPaths.add(path);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return usbPaths;
}

簡書: http://m.itdecent.cn/p/a32e376ea70e
CSDN: https://blog.csdn.net/qq_32115439/article/details/80918046
GitHub博客: http://lioil.win/2018/07/04/Android-USB-OTG.html
Coding博客: http://c.lioil.win/2018/07/04/Android-USB-OTG.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,351評論 25 708
  • afinalAfinal是一個android的ioc,orm框架 https://github.com/yangf...
    wgl0419閱讀 6,602評論 1 9
  • afinalAfinal是一個android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,899評論 2 45
  • 每個人都有記憶中的味道,但同時所有記憶中的味道又都是不一樣的。 我叫倩倩,出生于陜西省、銅川市的礦醫(yī)院...
    回不去的曾經(jīng)2閱讀 270評論 0 1
  • 留心處處皆學問 人情練達即文章
    天賦文案閱讀 193評論 0 0

友情鏈接更多精彩內(nèi)容