android 7.0+、8.0+應用中點擊拍照崩潰的解決辦法


在開發中,項目里面明明已經添加過拍照或者讀取相冊的權限,但是在點擊拍照或者打開相冊的時候應用會崩潰,報一下錯誤:

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屬性,好了,今天就寫到這里。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM