car-eye 行车记录仪中的外部存储卡操作

在行车记录仪中,android各个版本对外部存储卡存在着权限上的限制,对获取卡的位置存在不同SDK版本上的差异,car-eye行车记录仪为了保持兼容性。做了最全面的处理:

获取卡的位置:

 public  String[] initDisk(Context context) {  
        String sd = null; 
        Class<?> storageVolumeClazz = null;  
        ArrayList<String> lineByteList = new ArrayList<String>();
        try { 
        StorageManager storageManager = (StorageManager) context  
                .getSystemService(Context.STORAGE_SERVICE);  
        storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");  
        Method getVolumeList = StorageManager.class.getDeclaredMethod("getVolumeList");                  
        Method isRemovable = storageVolumeClazz.getMethod("isRemovable");  
        Method getPath = storageVolumeClazz.getMethod("getPath");  
        Object  volumes = getVolumeList.invoke(storageManager);
        Method getVolumeState = StorageManager.class.getDeclaredMethod("getVolumeState", String.class); 
        final int length = Array.getLength(volumes);        
        for (int i = 0; i < length; i++) 
        {                     
         Object storageVolumeElement  = Array.get(volumes, i);               
         String path = (String) getPath.invoke(storageVolumeElement);  
             String state = (String) getVolumeState.invoke(storageManager, path); 
             boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);  
                if(Environment.MEDIA_MOUNTED.equals(state) && removable)
                {
                 lineByteList.add(path);
                 Log.d(tag, "Disk path  : " + path);
                }              
           
          }  
        } catch (Exception e)
        {  
                     Log.e(tag, e.getMessage());  
        }  
        path = new String [lineByteList.size()];
        for(int j = 0;j < lineByteList.size(); j++ ){
         path[j] = lineByteList.get(j);         
        }         
        return path;  

    }  

 权限:

public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);


   if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
}

}

对于6.0以上的ANDROID OS:

    if(version>=23)
{
verifyStoragePermissions(MainActivity.this);

}

同时在manifest中申明对卡的访问的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


这样就可以动态的获得卡的位置并对外部存储卡进行操作了。需要注意的是,如果还不能对卡进行读写

那么请对android设备进行root处理。

这样就能正常的访问外部存储卡了。

相关代码下载https://github.com/Car-eye-team  欢迎加入技术讨论群:590411159 

mark 下

猜你喜欢

转载自blog.csdn.net/dengtieshan1/article/details/79313400