//可以获取储存设备,包括U盘,此方法与adb通过storage获取的储存设备一致
public List<StorageInfo> listAllStorage(Context context) {
ArrayList<StorageInfo> storages = new ArrayList<StorageInfo>();
StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
try {
Class<?>[] paramClasses = {};
Method getVolumeList = StorageManager.class.getMethod("getVolumeList", paramClasses);
Object[] params = {};
Object[] invokes = (Object[]) getVolumeList.invoke(storageManager, params);
if (invokes != null) {
StorageInfo info = null;
for (int i = 0; i < invokes.length; i++) {
Object obj = invokes[i];
Method getPath = obj.getClass().getMethod("getPath", new Class[0]);
String path = (String) getPath.invoke(obj, new Object[0]);
info = new StorageInfo(path);
Method getVolumeState = StorageManager.class.getMethod("getVolumeState", String.class);
String state = (String) getVolumeState.invoke(storageManager, info.path);
info.state = state;
Method isRemovable = obj.getClass().getMethod("isRemovable", new Class[0]);
info.isRemoveable = ((Boolean) isRemovable.invoke(obj, new Object[0])).booleanValue();
storages.add(info);
}
}
} catch (Exception e) {
e.printStackTrace();
}
storages.trimToSize();
return storages;
}
//获取可用的设备
public static List<StorageInfo> getAvaliableStorage(List<StorageInfo> infos){
List<StorageInfo> storages = new ArrayList<StorageInfo>();
for(StorageInfo info : infos){
File file = new File(info.path);
if ((file.exists()) && (file.isDirectory()) && (file.canWrite())) {
if (info.isMounted()) {
storages.add(info);
}
}
}
return storages;
}
public class StorageInfo {
public String path;
public String state;
public boolean isRemoveable;
public StorageInfo(String path) {
this.path = path;
}
public boolean isMounted() {
return "mounted".equals(state);
}
@Override
public String toString() {
return "StorageInfo [path=" + path + ", state=" + state
+ ", isRemoveable=" + isRemoveable + "]";
}
}
//下面是简单使用上面的方法
public int checkFileIsExsit() {
List<StorageInfo> list = listAllStorage(m_context);
for(StorageInfo info : list){
//确认是否存在特定文件
m_sFilePath = info.path + "/" + filename;
MyLog.e("u盘路径: "+info.path + "/" + filename);
if (fileIsExists(m_sFilePath)) {
//Log.e(TAG, filePath + " is exists!");
return 0;
}
}
MyLog.e(m_sFilePath + " is not exists!");
return -1;
}
private static boolean fileIsExists(String filepath){
//Log.e(TAG, "file: " + filepath);
try{
File f = new File(filepath);
if(!f.exists()){
return false;
}
}catch (Exception e) {
MyLog.e(filepath + " not exists!");
return false;
}
return true;
}