參考:
https://developer.android.com/guide/topics/connectivity/usb/host.html
https://blog.csdn.net/qq_29924041/article/details/80141514
本文介紹Android手機(jī)通過(guò)OTG數(shù)據(jù)線讀寫USB存儲(chǔ)設(shè)備(U盤,移動(dòng)硬盤,存儲(chǔ)卡)的兩種方法
方法一: 直接和USB設(shè)備建立連接骇扇,借助第三方庫(kù)libaums識(shí)別U盤的文件系統(tǒng)
由于libaums只支持FAT32文件系統(tǒng),所以U盤的格式化必須采用FAT32!
該庫(kù)的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" />
// 手機(jī)必須支持USB主機(jī)特性(OTG)
<uses-feature android:name="android.hardware.usb.host" />
2.監(jiān)聽(tīng)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)限申請(qǐng)
test();
} else {
logShow("用戶未授權(quán),訪問(wèn)USB設(shè)備失敗");
}
}
break;
case UsbManager.ACTION_USB_DEVICE_ATTACHED://USB設(shè)備插入廣播
logShow("USB設(shè)備插入");
break;
case UsbManager.ACTION_USB_DEVICE_DETACHED://USB設(shè)備拔出廣播
logShow("USB設(shè)備拔出");
break;
}
}
};
private void init() {
//USB管理器
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
//注冊(cè)廣播,監(jiān)聽(tīng)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庫(kù)讀寫U盤文件
private void test() {
try {
UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
for (UsbMassStorageDevice storageDevice : storageDevices) { //一般手機(jī)只有一個(gè)USB設(shè)備
// 申請(qǐng)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("錯(cuò)誤: 讀取分區(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() + " ->復(fù)制到/sdcard/111/");
storageDevice.close();
}
} catch (Exception e) {
logShow("錯(cuò)誤: " + 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讀寫文件)
對(duì)于U盤的文件系統(tǒng)律胀,只依賴于手機(jī)系統(tǒng)是否支持伯襟,無(wú)需我們做額外工作(所有Android手機(jī)都支持FAT32,有個(gè)別手機(jī)還支持NTFS)
但是有些手機(jī)無(wú)法獲取掛載路徑(如小米等蛔外,就算通過(guò)mount命令找到掛載路徑也沒(méi)有權(quán)限讀寫)蛆楞,所以該方法通用性其實(shí)不如方法一!
1.通過(guò)MEDIA廣播獲取掛載路徑
// 注冊(cè)系統(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.通過(guò)反射系統(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;
}
簡(jiǎn)書(shū): http://www.reibang.com/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