在android项目中实现Windos一样的U盘效果,需监听两个U盘的插入和拔出状态,并屏蔽本地存储,使用U盘来下载和上传文件;
在编辑代码中碰到一个问题:无法获取插入U盘的名称,于是通过java的反射机制来调用源码的API获取,方法如下:
private void checkUdisk(){
//udisk_insert = false;
Class volumeInfoClazz = null;
Method getVolumes = null;
Method getPath = null;
Method getUserLabel = null;
Object[] volumes = null;
try {
volumeInfoClazz = Class.forName("android.os.storage.StorageVolume");
getVolumes = StorageManager.class.getMethod("getVolumeList");
getPath = volumeInfoClazz.getMethod("getPath");
getUserLabel = volumeInfoClazz.getMethod("getUserLabel");
volumes = (Object[])getVolumes.invoke(mStorageManager);
for (Object vol : volumes) {
String path = (String) getPath.invoke(vol);
if (path.indexOf("udisk0")!=-1){
String userLabel = (String) getUserLabel.invoke(vol);
// if (userLabel!=null){
// myApplication.setUserLabel0(userLabel);
// udisk_insert = true;
// }else {
// myApplication.setUserLabel0(null);
// }
}else if (path.indexOf("udisk1")!=-1){
String userLabel = (String) getUserLabel.invoke(vol);
// if (userLabel!=null){
// myApplication.setUserLabel1(userLabel);
// udisk_insert = true;
// }else {
// myApplication.setUserLabel1(null);
// }
}
}
// if (udisk_insert){
// handler_UD.sendEmptyMessage(0);
// }else {
// myApplication.setUserLabel0(null);
// myApplication.setUserLabel1(null);
// handler_UD.sendEmptyMessage(1);
// }
}catch (Exception ex) {
ex.printStackTrace();
}
}
在上面的方法中
volumeInfoClazz = Class.forName("android.os.storage.StorageVolume");
首先通过反射获取StorageVolume类
getVolumes = StorageManager.class.getMethod("getVolumeList");
然后获取类中的**getVolumeLis**t方法
getPath = volumeInfoClazz.getMethod("getPath");
getUserLabel = volumeInfoClazz.getMethod("getUserLabel");
获取U盘路径和U盘真实名称的方法
volumes = (Object[])getVolumes.invoke(mStorageManager);
获取数组对象
String path = (String) getPath.invoke(vol);
获取路径
android中U盘的闪存路径为storage/udisk0和storage/udisk1所以在代码中取出包括关键字的对象对应的userLabel也就是U盘名称
注意事项:
使用的SDK源码版本不同,会导致方法名不相同,上述方法中使用的是定制源码,直接复制代码会导致报错,使用改方法时,去对应的android\os目录下找到相应的类,和其中的方法,然后在代码中通过反射使用。