使用前提
手機(jī)必須支持OTG協(xié)議
USB硬盤(pán)格式必須是FAT32(libaums庫(kù)只支持FAT32,若其他格式請(qǐng)使用原生讀取方式)
集成libaums庫(kù)
在app/build.gradle文件導(dǎo)入library
dependencies {
implementation 'com.github.mjdev:libaums:0.7.1'
}
使用
查出USB設(shè)備
UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(this);
獲取原生USB管理對(duì)象
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
動(dòng)態(tài)獲取權(quán)限
PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
for (UsbMassStorageDevice device : devices) {
mUsbManager.requestPermission(device.getUsbDevice(), permissionIntent);
}
這時(shí)候,系統(tǒng)就會(huì)彈出提示框,“允許應(yīng)用“XXX”訪問(wèn)該USB設(shè)備嗎?”(不同廠商ROM可能有不同的提示),選擇確定即可接收到回執(zhí)廣播。
這里寫(xiě)一個(gè)廣播接收器來(lái)接收回執(zhí)
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:
}
}
};
然后就可以執(zhí)行文件的讀寫(xiě)操作了,這里先展示一下根目錄
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/計(jì)價(jià)器原始記錄/9-1
InputStream is = null;
try {
UsbFile file = root.search("計(jì)價(jià)器原始記錄").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("讀取記錄數(shù)據(jù)" + resultSb);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
創(chuàng)建文件并寫(xiě)入 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();
}
}