在開發中,項目里面明明已經添加過拍照或者讀取相冊的權限,但是在點擊拍照或者打開相冊的時候應用會崩潰,報一下錯誤:
Caused by: android.os.FileUriExposedException: file:///storage/emulated/0/com.yzs.nongfeike/20181105100312792.jpg exposed beyond app through ClipData.Item.getUri()
簡單查了一下是Android7.0+權限機制改變造成的。網上也有很多解決方法,有的需要在清單文件manifest中定義FileProvider,還需要在res下新建xml文件夾,並新建filepaths.xml.
個人感覺這種比較麻煩,現在貼上我親自測試有效的解決方法。
Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); min_photo = saveFolder + "/" + ImageUtil.getImageName(); file = new File(min_photo); int currentapiVersion = android.os.Build.VERSION.SDK_INT; //7.0以下 if (currentapiVersion<24){ intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); startActivityForResult(intentFromCapture, PHOTO); }else{ //7.0以上 ContentValues contentValues = new ContentValues(1); contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath()); Uri uri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues); intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intentFromCapture, PHOTO); }
其實很簡單,就是做一下手機安卓系統判定,7.0以下的執行原始調用方式。7.0以上的需要使用ContentValues屬性,好了,今天就寫到這里。