android 4.4 5.0不能獲取到圖片路徑問題詳解
最近在做一個從相簿選擇圖片或拍照,然後裁剪的功能.本來是沒問題的,一直在用
- Intent intent=new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
而這個圖片選擇器可以遮蔽掉那個auto backup的目錄.所以就開始打算用這個圖片選擇器來選圖片了.
這個方法就是
- Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
- intent.addCategory(Intent.CATEGORY_OPENABLE);
- intent.setType("image/jpeg");
-
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){
- startActivityForResult(intent, SELECT_PIC_KITKAT);
- }else{
- startActivityForResult(intent, SELECT_PIC);
- }
為什麼要分開不同版本呢?其實在4.3或以下可以直接用ACTION_GET_CONTENT的,在4.4或以上,官方建議用ACTION_OPEN_DOCUMENT,但其實都不算太大區別,區別是他們返回的Uri,那個才叫大區別.這就是困擾了我一整天的問題所在了.
4.3或以下,選了圖片之後,根據Uri來做處理,很多帖子都有了,我就不詳細說了.主要是4.4,如果使用上面pick的原生方法來選圖,返回的uri還是正常的,但如果用ACTION_GET_CONTENT的方法,返回的uri跟4.3是完全不一樣的,4.3返回的是帶檔案路徑的,而4.4返回的卻是content://com.android.providers.media.documents/document/image:3951這樣的,沒有路徑,只有圖片編號的uri.這就導致接下來無法根據圖片路徑來裁剪的步驟了.
還好找了很多方法,包括加許可權啊什麼的,中間還試過用一些方法,自己的app沒崩潰,倒是讓系統圖庫崩潰了,引發了java.lang.SecurityException.
- Caused by: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord{437b5d88 9494:com.google.android.gallery3d/u0a20} (pid=9494, uid=10020) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS
看來4.4的系統還是有些bug.重點來了,4.4得到的uri,需要以下方法來獲取檔案的路徑
- publicstatic String getPath(final Context context, final Uri uri) {
- finalboolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
- // DocumentProvider
- if (isKitKat && 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)) {
- return Environment.getExternalStorageDirectory() + "/" + split[1];
- }
- // TODO handle non-primary volumes
- }
- // DownloadsProvider
- elseif (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
- elseif (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;
- } elseif ("video".equals(type)) {
- contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
- } elseif ("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)
- elseif ("content".equalsIgnoreCase(uri.getScheme())) {
- // Return the remote address
- if (isGooglePhotosUri(uri))
- return uri.getLastPathSegment();
- return getDataColumn(context, uri, null, null);
- }
- // File
- elseif ("file".equalsIgnoreCase(uri.getScheme())) {
- return uri.getPath();
- }
- returnnull;
- }
- /**
- * Get the value of the data column for this Uri. This is useful for
- * MediaStore Uris, and other 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.
- */
- publicstatic 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()) {
- finalint index = cursor.getColumnIndexOrThrow(column);
- return cursor.getString(index);
- }
- } finally {
- if (cursor != null)
- cursor.close();
- }
- returnnull;
- }
- /**
- * @param uri The Uri to check.
- * @return Whether the Uri authority is ExternalStorageProvider.
- */
- publicstaticboolean isExternalStorageDocument(Uri uri) {
- return"com.android.externalstorage.documents".equals(uri.getAuthority());
- }
- /**
- * @param uri The Uri to check.
- * @return Whether the Uri authority is DownloadsProvider.
- */
- publicstaticboolean isDownloadsDocument(Uri uri) {
- return"com.android.providers.downloads.documents".equals(uri.getAuthority());
- }
- /**
- * @param uri The Uri to check.
- * @return Whether the Uri authority is MediaProvider.
- */
- publicstaticboolean isMediaDocument(Uri uri) {
- return"com.android.providers.media.documents".equals(uri.getAuthority());
- }
- /**
- * @param uri The Uri to check.
- * @return Whether the Uri authority is Google Photos.
- */
- publicstaticboolean isGooglePhotosUri(Uri uri) {
- return"com.google.android.apps.photos.content".equals(uri.getAuthority());
- }
這樣,就可以在4.4上用漂亮的圖片選擇器,選到我們想要的檔案,又不會出問題了.
昨天發現了個bug,如果在4.4上面不用"圖片"來選,用"相簿"來選,就會無法讀取到圖片路徑,所以只需要加個判斷,如果是用舊方式來選,就用舊方式來讀,就是如果
DocumentsContract.isDocumentUri(context, uri) 返回false的話,就用舊的方式
- publicstatic String selectImage(Context context,Intent data){
- Uri selectedImage = data.getData();
- // Log.e(TAG, selectedImage.toString());
- if(selectedImage!=null){
- String uriS