1. 程式人生 > >Android 開發 之 異常android.os.FileUriExposedException: file:///storage/emulated/0/

Android 開發 之 異常android.os.FileUriExposedException: file:///storage/emulated/0/

原因:

Android N對訪問檔案許可權收回,按照Android N的要求,若要在應用間共享檔案,您應傳送一項 content://URI,並授予 URI 臨時訪問許可權。 

而進行此授權的最簡單方式是使用 FileProvider類。

解決方案:

1.在manifest檔案中註冊一個provider

<application>
 ......
     <provider
         android:authorities="你的應用名.fileprovider"
         android:name="android.support.v4.content.FileProvider"
         android:grantUriPermissions="true"
         android:exported="false">
         <meta-data
           android:name="android.support.FILE_PROVIDER_PATHS"
               android:resource="@xml/filepaths"/>
    </provider>

</application>

ps:1.android:authorities屬性必須全域性一樣,例如主工程和library功能中必須是同一個字串;(編譯可以通過,執行會崩潰)

        2.android:name 屬性是不能一致的,必須使用不同包名下的FileProvider,繼承FileProvider;(不然編譯不過去)

2.在res中建立一個xml資料夾,在資料夾中建立filepaths.xml檔案
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-cache-path
        name="external_cache_path"
        path="" />

</paths>
path 代表要共享的目錄 
name 只是一個標示,隨便取吧 自己看的懂就ok


例如:共享這個目錄

//mContext.getExternalCacheDir()+"/aaa.png"
則:name隨便;path=" ";path為空串就可以了;
//mContext.getExternalCacheDir()+"/myfile/aaa.png"
則:name隨便;path="myfile";

3.程式碼:
    /**
     * 開啟相機
     */
    public void openCamera() {
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(mContext.getExternalCacheDir(), getPhotoFileName());
        //mContext.getExternalCacheDir()+"/myfile/aaa.png"
        photoFileName = file.getAbsolutePath();
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(mContext.getApplicationContext(), "com.xmen.xteam.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        ((Activity)mContext).startActivityForResult(intent,PictureAdapter.REQUEST_CODE);
    }