基于OTG技术,使用第三方库libaums实现在Android设备上读写USB设备信息

使用前提

手机必须支持OTG协议

USB硬盘格式必须是FAT32(libaums库只支持FAT32,若其他格式请使用原生读取方式)

集成libaums库

Github地址

在app/build.gradle文件导入library

dependencies {
    implementation 'com.github.mjdev:libaums:0.7.1'
}

使用

查出USB设备

UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(this);

获取原生USB管理对象

UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

动态获取权限

PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
for (UsbMassStorageDevice device : devices) {
    mUsbManager.requestPermission(device.getUsbDevice(), permissionIntent);
}

这时候,系统就会弹出提示框,“允许应用“XXX”访问该USB设备吗?”(不同厂商ROM可能有不同的提示),选择确定即可接收到回执广播。

这里写一个广播接收器来接收回执

private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action == null) {
            return;
        }
        switch (action) {
            case ACTION_USB_PERMISSION:
        }
    }
};

然后就可以执行文件的读写操作了,这里先展示一下根目录

for (UsbMassStorageDevice device : devices) {
    // before interacting with a device you need to call init()!
    try {
        device.init();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Only uses the first partition on the device
    FileSystem currentFs = device.getPartitions().get(0).getFileSystem();
    try {
        UsbFile root = currentFs.getRootDirectory();
        UsbFile[] files = root.listFiles();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

读取文件, root/计价器原始记录/9-1

InputStream is = null;
try {
    UsbFile file = root.search("计价器原始记录").search("9-1");

    // read from a file
    is = new UsbFileInputStream(file);
    InputStreamReader inputStreamReader = new InputStreamReader(is, "GBK");
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    String tempLine;
    StringBuilder resultSb = new StringBuilder();
    while ((tempLine = bufferedReader.readLine()) != null) {
        System.out.println(tempLine);
        resultSb.append(tempLine).append("\n");
    }
    System.out.println("读取记录数据" + resultSb);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (is != null) {
            is.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

创建文件并写入 root/foo/bar.txt

OutputStream os = null;
try {
    UsbFile newDir = root.createDirectory("foo");
    UsbFile file = newDir.createFile("bar.txt");
    // write to a file
    os = new UsbFileOutputStream(file);
    os.write("hello".getBytes());
    os.close();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

你可能感兴趣的:(基于OTG技术,使用第三方库libaums实现在Android设备上读写USB设备信息)