判断U盘是否挂载和获取U盘路径
正常可以通过广播来监听U盘的挂载状态,如果刚开机未收到开机广播就需要获取U盘状态
1.判断U盘是否挂载
public static boolean getUsb(StorageManager storageManager) {
try {
Class<?> cls = Class.forName("android.os.storage.VolumeInfo");
cls.getMethod("getDescriptionComparator", new Class[0]);
Method method = StorageManager.class.getMethod("getBestVolumeDescription", cls);
Method method2 = StorageManager.class.getMethod("getVolumes", new Class[0]);
Method method3 = cls.getMethod("isMountedReadable", new Class[0]);
Method method4 = cls.getMethod("getType", new Class[0]);
Method method5 = cls.getMethod("getPath", new Class[0]);
for (Object obj : (List) method2.invoke(storageManager, new Object[0])) {
if (obj != null && ((Boolean) method3.invoke(obj, new Object[0])).booleanValue() && ((Integer) method4.invoke(obj, new Object[0])).intValue() == 0) {
String path = ((File) method5.invoke(obj, new Object[0])).getPath();
Log.d(TAG, "-----------path1-----------------" + ((String) method.invoke(storageManager, obj)));
Log.d(TAG, "-----------path2 @@@@@-----------------" + path);
if (path != null && !"".equals(path)) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
2.广播监听U盘状态
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
Log.e(TAG, "USB=MOUNTED");
handler.sendEmptyMessage(StatusConstant.Usb.MOUNTED);
} else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) {
Log.e(TAG, "USB=UNMOUNTED");
handler.sendEmptyMessage(StatusConstant.Usb.UNMOUNTED);
}
}
}
3.获取U盘路径
ArrayList<String> usbPathList = new ArrayList<String>();
usbCount = 0;
StorageManager sm = (StorageManager) this.getSystemService(Context.STORAGE_SERVICE);
for (StorageVolume volume : sm.getVolumeList()) {
if ((!volume.getPath().contains("emulated")) && volume.getState().equals("mounted")) {
usbPathList.add(volume.getPath());
usbCount++;
continue;
}
}