对于U盘的文件系统,只依赖于手机系统是否支持,无需我们做额外工作(所有Android手机都支持FAT32,有个别手机还支持NTFS) 但是有些手机无法获取挂载路径(如小米等,就算通过mount命令找到挂载路径也没有权限读写),所以该方法通用性其实不如方法一!
1.通过MEDIA广播获取挂载路径
// 注册系统广播
<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.通过反射系统方法获取挂载路径
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;
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号