Android7.0適配APK安裝
適配的原因
對於面向Android7.0的應用,Android框架執行的StrictMode API政策禁止在您的應用外部公開file://URL。如果一項包含文件URL的intent離開您的應用,則應用出現故障,並出現FileUriExposedException異常。
要在應用間共享文件,您應發送一項content://URL,並授予URL臨時訪問權限。進行此授權的最簡單方式是使用FileProvider類。
官網文章地址:https://developer.android.google.cn/reference/android/support/v4/content/FileProvider?hl=zh-cn
上面的兩段話來自Android開發者平台的版本Android7.0行為變更中。
由於調用系統的安裝,需要傳遞一個Uri對象,導致包含文件URL的intent離開了本應用,所以導致報錯,安裝APK的代碼無法在Android7.0上正常使用,所以要進行修改獲取Uri的方式。
適配的方法
從官方文檔中看到需要使用FileProvider類來授予URL臨時訪問權限,依次來解決安裝APK的問題。
使用FileProvider分為三個步驟:
1.在AndroidMainfest.xml文件中聲明FileProvider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.readboy.lee.AppUpdate.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
注意:android:authorities
的值,最好設為包名+“fileprovider”,如果有兩個應用都注冊了同樣的FileProvider,是會報錯的。
2.添加資源文件
在AndroidMainfest.xml中聲明的FileProvider中android:resource
的值對應的文件需要我們自己添加,在res文件夾下創建一個xml文件夾,並創建file_paths.xml文件。如果已經有xml文件夾,則直接創建file_paths.xml文件即可。
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="files-path" path="/." />
<cache-path name="cache-path" path="/." />
<external-path name="external-path" path="/." />
<external-files-path name="external-files-path" path="/." />
<external-cache-path name="external-cache-path" path="/." />
</paths>
上面的就是file_paths.xml里面的內容。
paths里面的界面分別代表:
<files-path/>
代表context.getFileDir()
<cache-path/>
代表context.getCacheDir()
<external-path/>
代表Environment.getExternalStorageDirectory()
<external-files-path/>
代表context.getExternalFilesDirs()
<external-cache-path/>
代表context.getExternalCacheDirs()
path="/."
表示的是當前目錄下的所有目錄。
注意:如果你選擇吧這些選項全部都加到資源文件中,那么這些條目的name
屬性值要互不相同。
聲明之后,代碼中就可以使用所聲明的當前文件夾以及其子文件夾。
3.在代碼中使用FileProvider
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri uri = FileProvider.getUriForFile(context,"com.readboy.lee.AppUpdate.fileprovider",new File(path));
intent.setDataAndType(uri,"application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
intent.setDataAndType(Uri.parse("file://" + path),"application/vnd.android.package-archive");
}
context.startActivity(intent);
當SDK大於等於7.0時,使用FileProvider獲取Uri值,然后再傳遞出去。
總結
因為看網上的這塊,踩了很多坑,自己總結一下,方便后期的查看。