2016-05-26
9:42 AM
有時使用檔案選擇器取得路徑時會發現路徑是奇怪的 content://downloads/public_downloads 字串
而這種路徑使用 context.getContentResolver().query(); 方法取得的路徑會是空的
其實是因為新版 Android 在路徑上是使用 uri 的方式表示的
有點像網址,好處是同一個 uri 可以指定到不同的實體路徑內
用以對應不同的開發商與使用者設定
壞處就是取得路徑的方法變得較麻煩(而且官方文件似乎找不到方法? WTF?)
而且很多類型的檔案取得路徑的方式也沒有統一
以下就是對應各版本(4.4 以上)取得路徑的 FileUtil 的原始碼
檔案瀏覽器的使用方式可以到 啟動檔案瀏覽器選擇檔案 教學查看
程式碼範例
import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import cmc.toolkit.FileKit; import com.ihad.ptt.model.exception.EmptyFilePathException; import com.ihad.ptt.model.exception.IllegalTrueTypeFontException; import java.io.File; import java.io.FileNotFoundException; public class FileUtils { /** * 從 uri 取得檔案路徑 這將從 Storage Access Framework Documents 取得路徑 * 也會使用從 _data 欄位取得 MediaStore 以及其他 file-based ContentProviders 的對應路徑 * * @param context The context. * @param uri The Uri to query. * @author paulburke */ public static String getPath(final Context context, final Uri uri) { // DocumentProvider if ( DocumentsContract.isDocumentUri(context, uri) ) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { String path = Environment.getExternalStorageDirectory().getPath(); if (split.length > 1) { path += "/" + split[1]; } return path; } else { String path; if (Environment.isExternalStorageRemovable()) { path = System.getenv("EXTERNAL_STORAGE"); } else { path = System.getenv("SECONDARY_STORAGE"); if (path == null || path.length() == 0) { path = System.getenv("EXTERNAL_SDCARD_STORAGE"); } } if (split.length > 1) { path += "/" + split[1]; } return path; } } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * 從 data 欄位取得 uri 對應的實體路徑 * 主要用以取得 MediaStore Uris 以及其他 file-based ContentProviders 的對應路徑 * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. * @author paulburke */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int column_index = cursor.getColumnIndexOrThrow(column); return cursor.getString(column_index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * @param uri The Uri to check. * @return 是否為 ExternalStorageProvider 類型的 uri * @author paulburke */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return 是否為 DownloadsProvider 類型的 uri * @author paulburke */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return MediaProvider 類型的 uri * @author paulburke */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return 是否為 Google Photos 類型的 uri */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); } // 檢查檔案類型的小範例 /** * 檢查取回的檔案副檔名 * @param path 檔案路徑 * @return * 若檔案類型正確則回傳檔案名稱, 反之則回傳空字串 * @throws EmptyFilePathException 路徑是空字串或是 null 物件 * @throws FileNotFoundException 檔案不存在 * @throws IllegalTrueTypeFontException 檔案類型不正確 */ public static String typefaceChecker(String path) throws EmptyFilePathException, FileNotFoundException, IllegalTrueTypeFontException { if( path == null || path.isEmpty() ){ throw new EmptyFilePathException( "File path is empty" ); } File file = new File(path); if( !file.exists() || !file.isFile() ) { throw new FileNotFoundException( "File path : " + path ); } String filename = file.getName(); String ext = FileKit.getFileExt(filename); if( !ext.equalsIgnoreCase(".ttf") ){ throw new IllegalTrueTypeFontException( "File path : " + path + ", File name : " + filename + ", ext : " + ext ); } return filename; } }
各項資料連結
啟動檔案瀏覽器選擇檔案
Stackoverflow - Get real path from URI, Android KitKat new storage access framework
GitHub - aFileChooser
JTG Marriott Resort & Casino: Casino, Restaurants, Lodging
ReplyDeleteJOIN now at JTG Marriott Resort & 의정부 출장마사지 Casino! We're the best hotel 문경 출장안마 in Las Vegas and it's 천안 출장안마 been 25 계룡 출장안마 years since we first 충주 출장마사지 opened!