Android 机顶盒中获取U盘的卷标

来源:互联网 发布:小智代练淘宝店网址 编辑:程序博客网 时间:2024/05/29 21:28

最近,在开发Android 机顶盒中,遇到需要打印U盘的卷标问题。通过查阅资料,记录一下学习过程。

卷标,用通俗的话来说,就是U盘的名称

如图:在windows系统中,F:为盘符

           MQUDISK为U盘名称,也是卷标。

在Linux系统中,一般只会显示U盘的挂载路径,并没有显示盘符。

在Android开发中,如果需要显示U盘的名称,则需要额外写代码获取。


在代码中的体现:


private StorageManager mStorageManager;

在onCreate()方法中,添加系统权限

mStorageManager = (StorageManager)getSystemService(Context.STORAGE_SERVICE);


关键方法:通过反射的方法(具体原理,我也不清楚,原谅我还是小白)

public class UsbReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "intent  " + intent);
if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) {
//external storage
                Class<?> volumeInfoClazz = null;
                Method getDescriptionComparator = null;
                Method getBestVolumeDescription = null;
                Method getVolumes = null;
                Method isMountedReadable = null;
                Method getType = null;
                Method getPath = null;
                List<?> volumes = null;
                try {
                    volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo");
                    getDescriptionComparator = volumeInfoClazz.getMethod("getDescriptionComparator");
                    getBestVolumeDescription = StorageManager.class.getMethod("getBestVolumeDescription", volumeInfoClazz);
                    getVolumes = StorageManager.class.getMethod("getVolumes");
                    isMountedReadable = volumeInfoClazz.getMethod("isMountedReadable");
                    getType = volumeInfoClazz.getMethod("getType");
                    getPath = volumeInfoClazz.getMethod("getPath");
                    volumes = (List<?>)getVolumes.invoke(mStorageManager);

                    for (Object vol : volumes) {
                        if (vol != null && (boolean)isMountedReadable.invoke(vol) && (int)getType.invoke(vol) == 0) {
                            File path2 = (File)getPath.invoke(vol);
                            String p1 = (String)getBestVolumeDescription.invoke(mStorageManager, vol);
                            String p2 = path2.getPath();
                            Log.d(TAG,"-----------path2-----------------"+p1);                             //打印U盘卷标名称
                            Log.d(TAG,"-----------path2 @@@@@-----------------"+p2);         //打印U盘路径
                        }
                    }
                }catch (Exception ex) {
                    ex.printStackTrace();
                }

   }

}


在此,我还有一个疑问,当前打印出来的U盘名称(如果含有汉字)则为乱码,不知道该怎么解决?

麻烦有知道解决方法的告知一下,谢谢~


0 0
原创粉丝点击