2011-09-05 50 views
5

我想从astro管理器(在我的情况下是* .pdf或* .doc)中选择一个文件(通过文件选择器),但uri只包含文件路径("sdcard/my_folder/test.pdf")。对于我的应用程序,我需要像来自图像选择器(content:// media/external/images/media/2 )的内容路径。有没有办法将"file:///"转换为"content://" uri?转换文件uri到内容uri

或者有任何人有其他想法如何解决这个问题?

问候

UPDATE:主要的问题是,经过我选择我的文件选择与valuecallback.onReceiveValue(URI)方法文件的路径添加一个“/”后面。所以我得到这样的URI:“SD卡/ my_folder/test.pdf /”和我的应用程序认为pdf是一个文件夹。当我使用图像选择器的内容uri时,它起作用。

+0

SD卡/ my_folder /测试.pdf这是从移动设备读取数据从SD卡的正确的url –

回答

11

像@CommmonsWare说的那样,没有简单的方法可以将任何类型的文件转换为内容://。
但这里是我如何将图像转换成文件内容://

public static Uri getImageContentUri(Context context, File imageFile) { 
    String filePath = imageFile.getAbsolutePath(); 
    Cursor cursor = context.getContentResolver().query(
      MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
      new String[] { MediaStore.Images.Media._ID }, 
      MediaStore.Images.Media.DATA + "=? ", 
      new String[] { filePath }, null); 

    if (cursor != null && cursor.moveToFirst()) { 
     int id = cursor.getInt(cursor 
       .getColumnIndex(MediaStore.MediaColumns._ID)); 
     Uri baseUri = Uri.parse("content://media/external/images/media"); 
     return Uri.withAppendedPath(baseUri, "" + id); 
    } else { 
     if (imageFile.exists()) { 
      ContentValues values = new ContentValues(); 
      values.put(MediaStore.Images.Media.DATA, filePath); 
      return context.getContentResolver().insert(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); 
     } else { 
      return null; 
     } 
    } 
} 
+0

我试过这个 - file:///storage/emulated/0/Android/data/com.pkg_name/files/out.mp4,但它返回* null *。我也尝试将'MediaStore.Images.Media'改为'MediaStore.Video.Media',但仍然没有运气 – NarendraJi

+0

谢谢,这是我的Android-N设备上唯一适用于我的解决方案。我的应用程序的目标是API 24. – zeeshan

+0

@Ben Lee当我试图在位图中解码这个图像时,它返回null。 –

5

这里有一个简单的方法来考虑,这可能是适合你的。

我用它在谷歌加上我的Android应用程序共享下载的图像:

/** 
* Converts a file to a content uri, by inserting it into the media store. 
* Requires this permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
*/ 
protected static Uri convertFileToContentUri(Context context, File file) throws Exception { 

    //Uri localImageUri = Uri.fromFile(localImageFile); // Not suitable as it's not a content Uri 

    ContentResolver cr = context.getContentResolver(); 
    String imagePath = file.getAbsolutePath(); 
    String imageName = null; 
    String imageDescription = null; 
    String uriString = MediaStore.Images.Media.insertImage(cr, imagePath, imageName, imageDescription); 
    return Uri.parse(uriString); 
} 
0

一种简单的方法来实现,这可能是通过使用MediaScannerConnection

File file = new File("pathname"); 
MediaScannerConnection.scanFile(getContext(), new String[]{file.getAbsolutePath()}, null /*mimeTypes*/, new MediaScannerConnection.OnScanCompletedListener() { 
      @Override 
      public void onScanCompleted(String s, Uri uri) { 
       // uri is in format content://... 
      } 
     });