android 7.0 檔案獲取正確姿勢

android快速開發工具類
關於
Fastandrutils 是一套整理修改整合的android開發常用的工具類。
這樣可以減少複製貼上程式碼,從而減少重複程式碼,也不用為了一個常用的功能去谷歌百度,讓程式碼更簡潔,讓開發更高效。
同時希望您的新增完善,讓android開發變得更簡單。
在SDK升級到Android N,通過Uri.fromFile(file)獲取Uri報 android.os.FileUriExposedException異常,因為在Android 7.0系統上,Android框架強制執行了StrictMode API政策禁止嚮應用外公開file:// URI, 如果Intent包含了file://型別的URI離開應用,丟擲異常,退出程式。
正確姿勢一
粗暴解決問題
// 置入一個不設防的VmPolicy(不設定的話 7.0以上一呼叫拍照功能就崩潰) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); }
正確姿勢二
正常流程
使用FileProvider
1.配置AndroidManifest.xml
新增
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths" /><!-- 對應xml資料夾下的provider_paths.xml --> </provider>
2.在res資料夾下外掛xml資料夾
- xml資料夾下建立provider_paths.xml
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <root-path name="root" path="" /> </paths>
- 程式碼獲取Uri
Uri uri = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile(getContext(), authorities, new File(filePath)); } else { uri = Uri.fromFile(new File(filePath)); }
完畢