开启文件管理时 URI获取文件路径为null的解决方法

来源:互联网 发布:域名能不能绑定多个ip 编辑:程序博客网 时间:2024/06/07 19:15

最近做Android图片相关的开发,通过intent 得到 URI获取的文件路径为null,正好这篇文章解决了我的问题,mark一下

点击打开链接

原文:


今天调用系统自带的FileChooser后,根据Intent返回的uri获取路径的时一直返回null。

这个问题很奇怪,最后发现验证用的华为P7是Android 4.4系统。

先看下4.4之前的uri的形式:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Uri : content://media/extenral/images/media/17766  

是不是很熟悉?再看4.4及以后的Uri形式:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. content://com.android.providers.media.documents/document/image%2706  

    日志一打印出来我就明白是什么原因啦。这什么东西在Android 4.4前后不一样,4.4之前content后面是文件全路径,4.4之后不再直接表示路径啦。这就好办啦,翻了翻API后发现4.4以后的Uri还不唯一,并不是统一的一种格式,所以就来个通用解决办法好啦:

4.4以前通过Uri获取路径:data是Uri,filename是一个String的字符串,用来保存路径。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public static String getPathByUri(Context context, Uri data) {  
  2.         String filename=null;  
  3.         if (data.getScheme().toString().compareTo("content") == 0) {  
  4.             Cursor cursor = context.getContentResolver().query(data, new String[] { "_data" }, nullnullnull);  
  5.             if (cursor.moveToFirst()) {  
  6.                 filename = cursor.getString(0);  
  7.             }  
  8.         } else if (data.getScheme().toString().compareTo("file") == 0) {// file:///开头的uri  
  9.             filename = data.toString();  
  10.             filename = data.toString().replace("file://""");// 替换file://  
  11.             if (!filename.startsWith("/mnt")) {// 加上"/mnt"头  
  12.                 filename += "/mnt";  
  13.             }  
  14.         }  
  15.         return filename;  
  16.     }  
    4.4以后根据Uri获取路径:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使  
  2.     @SuppressLint("NewApi")  
  3.     public static String getPathByUri4kitkat(final Context context, final Uri uri) {  
  4.         final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;  
  5.         // DocumentProvider  
  6.         if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {  
  7.             if (isExternalStorageDocument(uri)) {// ExternalStorageProvider  
  8.                 final String docId = DocumentsContract.getDocumentId(uri);  
  9.                 final String[] split = docId.split(":");  
  10.                 final String type = split[0];  
  11.                 if ("primary".equalsIgnoreCase(type)) {  
  12.                     return Environment.getExternalStorageDirectory() + "/" + split[1];  
  13.                 }  
  14.             } else if (isDownloadsDocument(uri)) {// DownloadsProvider  
  15.                 final String id = DocumentsContract.getDocumentId(uri);  
  16.                 final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),  
  17.                         Long.valueOf(id));  
  18.                 return getDataColumn(context, contentUri, nullnull);  
  19.             } else if (isMediaDocument(uri)) {// MediaProvider  
  20.                 final String docId = DocumentsContract.getDocumentId(uri);  
  21.                 final String[] split = docId.split(":");  
  22.                 final String type = split[0];  
  23.                 Uri contentUri = null;  
  24.                 if ("image".equals(type)) {  
  25.                     contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;  
  26.                 } else if ("video".equals(type)) {  
  27.                     contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;  
  28.                 } else if ("audio".equals(type)) {  
  29.                     contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;  
  30.                 }  
  31.                 final String selection = "_id=?";  
  32.                 final String[] selectionArgs = new String[] { split[1] };  
  33.                 return getDataColumn(context, contentUri, selection, selectionArgs);  
  34.             }  
  35.         } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore  
  36.                                                                     // (and  
  37.                                                                     // general)  
  38.             return getDataColumn(context, uri, nullnull);  
  39.         } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File  
  40.             return uri.getPath();  
  41.         }  
  42.         return null;  
  43.     }  
  44.   
  45.     /** 
  46.      * Get the value of the data column for this Uri. This is useful for 
  47.      * MediaStore Uris, and other file-based ContentProviders. 
  48.      *  
  49.      * @param context 
  50.      *            The context. 
  51.      * @param uri 
  52.      *            The Uri to query. 
  53.      * @param selection 
  54.      *            (Optional) Filter used in the query. 
  55.      * @param selectionArgs 
  56.      *            (Optional) Selection arguments used in the query. 
  57.      * @return The value of the _data column, which is typically a file path. 
  58.      */  
  59.     public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {  
  60.         Cursor cursor = null;  
  61.         final String column = "_data";  
  62.         final String[] projection = { column };  
  63.         try {  
  64.             cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);  
  65.             if (cursor != null && cursor.moveToFirst()) {  
  66.                 final int column_index = cursor.getColumnIndexOrThrow(column);  
  67.                 return cursor.getString(column_index);  
  68.             }  
  69.         } finally {  
  70.             if (cursor != null)  
  71.                 cursor.close();  
  72.         }  
  73.         return null;  
  74.     }  
  75.   
  76.     /** 
  77.      * @param uri 
  78.      *            The Uri to check. 
  79.      * @return Whether the Uri authority is ExternalStorageProvider. 
  80.      */  
  81.     public static boolean isExternalStorageDocument(Uri uri) {  
  82.         return "com.android.externalstorage.documents".equals(uri.getAuthority());  
  83.     }  
  84.   
  85.     /** 
  86.      * @param uri 
  87.      *            The Uri to check. 
  88.      * @return Whether the Uri authority is DownloadsProvider. 
  89.      */  
  90.     public static boolean isDownloadsDocument(Uri uri) {  
  91.         return "com.android.providers.downloads.documents".equals(uri.getAuthority());  
  92.     }  
  93.   
  94.     /** 
  95.      * @param uri 
  96.      *            The Uri to check. 
  97.      * @return Whether the Uri authority is MediaProvider. 
  98.      */  
  99.     public static boolean isMediaDocument(Uri uri) {  
  100.         return "com.android.providers.media.documents".equals(uri.getAuthority());  
  101.     }  

    安卓2.3.3 & 4.0.4 & 4.4 & 5.1.1 & 6.0真机亲测都正常,欢迎拷贝!

    最后,附上一个Video项目用到的相关函数供参考:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //return the id of URI  
  2.     public static int getVideoUriByPath(Uri resultUri, Activity activity, String path){  
  3.         resultUri= null;  
  4.         int id=-1;  
  5.         if(activity==null || path==null)  
  6.             return id;  
  7.         Uri preUri = Uri.parse("content://media/external/video/media/");   
  8.         @SuppressWarnings("deprecation")  
  9.         Cursor cursor = activity.managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, nullnullnull, MediaStore.Video.Media.DEFAULT_SORT_ORDER);  
  10.         cursor.moveToFirst();  
  11.         while (!cursor.isAfterLast()) {  
  12.             String data = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));  
  13.             if (path.equals(data)) {  
  14.                 id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));  
  15.                 resultUri = Uri.withAppendedPath(preUri, "" + id);  
  16.                 break;  
  17.             }  
  18.             cursor.moveToNext();  
  19.         }  
  20.         return id;  
  21.     }  
我的启动方法


Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// CODE = 0
mcontext.startActivityForResult(intent, 0);




// 使用圖庫添加相片

if (requestCode == 0) {
if (resultCode == getActivity().RESULT_OK) {
ContentResolver cr = getActivity().getContentResolver();
Uri uri = data.getData();
Log.e("uri", " === " + uri);
Log.e("uri", "uri getAuthority= " + uri.getAuthority());
Cursor c = cr.query(uri,
new String[] { MediaStore.Images.Media.DATA }, null,
null, null);


String imgPath;
// 说明不是选的相册文件
if (null == c) {

imgPath = uri.getPath();
} else {
c.moveToFirst();
imgPath = c.getString(c
.getColumnIndex(MediaStore.Images.Media.DATA));
Log.e("path", "path = " + imgPath);
if (null == imgPath) {
imgPath = getPathByUri4kitkat(getActivity(), uri);
}
}
Log.e("path", "path = " + imgPath);
dealImg(imgPath);//处理文件的方法
}

0 0