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

要在應(yīng)用間共享文件,您應(yīng)發(fā)送一項(xiàng) content:// URI,并授予 URI 臨時(shí)訪問權(quán)限。進(jìn)行此授權(quán)的最簡(jiǎn)單方式是使用 FileProvider 類。
FileProvider 類的用法:
第一步:為您的應(yīng)用定義一個(gè)FileProvider清單條目,這個(gè)條目可以聲明一個(gè)xml文件,這個(gè)xml文件用來指定應(yīng)用程序可以共享的目錄。
<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 屬性應(yīng)該是唯一的,推薦使用【應(yīng)用包名+fileprovider】,推薦這樣寫
android:authorities=”${applicationId}.file_provider”,可以自動(dòng)找到應(yīng)用包名。
meta-data標(biāo)簽指定了一個(gè)路徑,這個(gè)路徑使用resource指定的xml文件來指明是那個(gè)路徑:
xml文件如下:
<?xml version="1.0" encoding="utf-8"?><paths> <external-files-path name="bga_upgrade_apk" path="upgrade_apk" /></paths>
Uri的獲取方式也要根據(jù)當(dāng)前Android系統(tǒng)版本區(qū)分對(duì)待:
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)); }這樣問題就解決了。貼上一個(gè)安裝apk適配7.0的例子://m.survivalescaperooms.com/article/113307.htm
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選