FileUriExposedException異常:file://與content://

在Android 版本7.0 以上
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N時,應用內提供給其他應用的文件路徑不能以file://格式提供,比如應用內自動更新跳轉安裝頁,使用系統相機裁剪功能。
原因:Android系統爲了安全隱私。
解決辦法 FileProvider + 傳遞content:// 格式的url。
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/file_paths" />
        </provider>

其中 file_paths 爲res下新建 xml文件下文件

//<external-path/>        
Environment.getExternalStorageDirectory(); /storage/emulated/0
//<external-cache-path/>     
getExternalCacheDir(); /storage/emulated/0/Android/data/包名/cache
//<external-files-path/>  
getExternalFilesDir(); /storage/emulated/0/Android/data/包名/files/Download 
//<cache-path/>         
getCacheDir();/data/user/0/包名/cache
//<files-path/>         
getFilesDir();   /data/user/0/包名/files
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_storage_root"
        path="." />
</paths>

這個例子中 使用 name=“external_storage_root” path="."。表示在/storage/emulated/0目錄下所有文件在傳遞的時候會將/storage/emulated/0 替換爲 external_storage_root


```java
file:///storage/emulated/0/QQBrowser/%E5%9B%BE%E7%89%87%E6%94%B6%E8%97%8F/d52a2834349b033b6ceadc1c1cce36d3d439bd91.jpg
變爲
content://包名.provider/external_storage_root/QQBrowser/%E5%9B%BE%E7%89%87%E6%94%B6%E8%97%8F/d52a2834349b033b6ceadc1c1cce36d3d439bd91.jpg

包名.provider對應的爲androidMainfest.xml中provider 的authorities屬性值

2 使用時 代碼中判斷版本號

Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    uri=FileProvider.getUriForFile(context,authorities屬性值,File文件);
    intent.addFlag(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}else{
	uri= Uri.fromFile(apkfile);
}

解決問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章