Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 7.0 拍照與圖片裁剪的 FileUriExposedException 適配詳解

編輯:關於 Android 程式設計

前言

Android 7.0 正式推出後,我拿到可以升級的 Nexus 6P 便開始著手適配。實測發現,在 7.0 以上版本執行相機拍照與圖片裁剪時,很容易撞上這兩類錯誤:

 Process: com.yuyh.imgsel, PID: 22995 // 錯誤1 android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/com.yuyh.imgsel/cache/1486438962645.jpg exposed beyond app through ClipData.Item.getUri() // 錯誤2 android.os.FileUriExposedException: file:///storage/emulated/0/DCIM/RxGalleryFinal/IMG_20161018180127.jpg exposed beyond app through Intent.getData()

根本原因在於:Android 7.0 之後改用 Content Uri 取代原本的 File Uri,因此當 targetSdkVersion=24 時,部分以 Uri.fromFile() 撰寫的寫法就不再適用。

File Uri 與 Content Uri 的差異

- File Uri 指向檔案本身的儲存路徑
- Content Uri 指向檔案在 Content Provider 中的路徑

所以在 7.0 以上版本,我們必須把 File Uri 轉換成 Content Uri。

具體轉換方法

 /** * 轉換 content:// uri * * @param imageFile * @return */ public Uri getImageContentUri(File imageFile) { String filePath = imageFile.getAbsolutePath(); Cursor cursor = 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 getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } }

有了這個方法,裁剪時就改成這樣呼叫:

 private void crop(String imagePath) { File file = new File("xxx.jpg"); cropImagePath = file.getAbsolutePath(); Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(getImageContentUri(new File(imagePath)), "image/*"); intent.putExtra("crop", "true"); intent.putExtra("aspectX", config.aspectX); intent.putExtra("aspectY", config.aspectY); intent.putExtra("outputX", config.outputX); intent.putExtra("outputY", config.outputY); intent.putExtra("scale", true); intent.putExtra("return-data", false); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()); intent.putExtra("noFaceDetection", true); startActivityForResult(intent, IMAGE_CROP_CODE); }

裁剪的問題到這裡就解決了。但是——拍照又會出狀況:

 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) { tempFile = new File(FileUtils.createRootPath(getActivity()) + "/" + System.currentTimeMillis() + ".jpg"); LogUtils.e(tempFile.getAbsolutePath()); FileUtils.createFile(tempFile); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile)); startActivityForResult(cameraIntent, REQUEST_CAMERA); }
 android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/com.yuyh.imgsel/cache/1486438962645.jpg exposed beyond app through ClipData.Item.getUri()

原因同樣是拍照輸出的檔案也必須以 Content Uri 的形式提供。解法是引入 FileProvider,分三步走。

Step 1:修改 AndroidManifest.xml

 <application ...> <provider android:name="android.support.v4.content.FileProvider" android:authorities="{替換為你的包名}.provider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"/> </provider> </application>

Step 2:在 res/xml/ 目錄下新增 provider_paths.xml

 <?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="https://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths>

Step 3:調整拍照時傳入的參數

 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getActivity(),BuildConfig.APPLICATION_ID + ".provider", tempFile)); //Uri.fromFile(tempFile)

總結

整條脈絡其實很單純:7.0 之後凡是需要把檔案交給其他應用程式讀寫的場合,都應該改用 Content Uri。裁剪用 MediaStore 反查 id 拼出 content:// 的 Uri,拍照則靠 FileProvider 產生授權 Uri,兩處都處理好,FileUriExposedException 自然就不再出現。以上就是本文的全部內容,若有疑問歡迎留言交流。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved