2011-09-05 46 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://... 
      } 
     });