Android 7.0行為變更 FileUriExposedException解決方法
Android 7.0行為變更 FileUriExposedException解決方法
當我們開發(fā)關于【在應用間共享文件】相關功能的時候,在Android 7.0上經(jīng)常會報出此運行時異常,那么Android 7.0以下沒問題的代碼,為什么跑到Android 7.0+的設備上運行就出問題了呢?,這主要來自于Android 7.0的一項【行為變更】!
對于面向 Android 7.0 的應用,Android 框架執(zhí)行的 StrictMode API 政策禁止在您的應用外部公開 file:// URI。如果一項包含文件 URI 的 intent 離開您的應用,則應用出現(xiàn)故障,并出現(xiàn) FileUriExposedException 異常。如圖:

要在應用間共享文件,您應發(fā)送一項 content:// URI,并授予 URI 臨時訪問權限。進行此授權的最簡單方式是使用 FileProvider 類。
FileProvider 類的用法:
第一步:為您的應用定義一個FileProvider清單條目,這個條目可以聲明一個xml文件,這個xml文件用來指定應用程序可以共享的目錄。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
...>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.myapp.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
...
</application>
</manifest>
在這段代碼中, android:authorities 屬性應該是唯一的,推薦使用【應用包名+fileprovider】,推薦這樣寫
android:authorities=”${applicationId}.file_provider”,可以自動找到應用包名。
meta-data標簽指定了一個路徑,這個路徑使用resource指定的xml文件來指明是那個路徑:
xml文件如下:
<?xml version="1.0" encoding="utf-8"?> <paths> <external-files-path name="bga_upgrade_apk" path="upgrade_apk" /> </paths>
Uri的獲取方式也要根據(jù)當前Android系統(tǒng)版本區(qū)分對待:
File dir = getExternalFilesDir("user_icon");
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
icon_path = FileProvider.getUriForFile(getApplicationContext(),
"com.mqt.android_headicon_cut.file_provider", new File(dir, TEMP_FILE_NAME));
} else {
icon_path = Uri.fromFile(new File(dir, TEMP_FILE_NAME));
}
這樣問題就解決了。貼上一個安裝apk適配7.0的例子:http://chabaoo.cn/article/113307.htm
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
源碼解析Android Jetpack組件之ViewModel的使用
Jetpack 是一個豐富的組件庫,它的組件庫按類別分為 4 類,分別是架構(Architecture)、界面(UI)、 行為(behavior)和基礎(foundation)。本文將從源碼和大家講講Jetpack組件中ViewModel的使用2023-04-04
Flutter開發(fā)之對角棋游戲實現(xiàn)實例詳解
這篇文章主要為大家介紹了Flutter開發(fā)之對角棋游戲實現(xiàn)實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
Android 實現(xiàn)永久性開啟adb 的root權限
這篇文章主要介紹了Android 實現(xiàn)永久性開啟adb 的root權限,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Android App仿QQ制作Material Design風格沉浸式狀態(tài)欄
這篇文章主要介紹了Android App仿QQ制作Material Design風格沉浸式狀態(tài)欄的實例,同時也給出了4.4版本下實現(xiàn)效果與5.0的對比,需要的朋友可以參考下2016-04-04
Android開發(fā)之Android.mk模板的實例詳解
這篇文章主要介紹了Android開發(fā)之Android.mk模板的實例詳解的相關資料,希望通過本文能幫助到大家,讓大家理解掌握這部分內容,需要的朋友可以參考下2017-10-10
Android使用 PopupWindow 實現(xiàn)底部彈窗功能
這篇文章主要介紹了Android使用 PopupWindow 實現(xiàn)底部彈窗功能,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12

