首先看一下安裝apk檔案的代碼
/**
* 通過隐式意圖調用系統安裝程式安裝APK
*/
public static void install(Context context) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "xxxx.apk")),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
測試發現該段代碼在7.0一下的機型上可以成功打開指定路徑下的指定apk檔案 , 但是在7.0+的機型上調用該代碼會報錯:
android.os.FileUriExposedException: file:///storage/emulated/0/Download/xxxx.apk exposed beyond app through Intent.getData()
原因在于:Android 7.0 版本開始 禁止向你的應用外公開 file:// URI。 如果一項包含檔案 file:// URI類型 的 Intent 離開你的應用,應用失敗,并出現 FileUriExposedException 異常。
解決方法:
一、在AndroidManifest.xml 檔案中添加 四大元件之一的 <provider>
<!-- 适配7.0 apk安裝 -->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.xxx.xxxx.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<!--中繼資料-->
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
注意這裡的 android :authorities 屬性的值 中的 com.xxx.xxxx 是你的包名,不可随意填寫
二、res 目錄下 建一個xml 檔案,并建立xml檔案file_paths.xml
注意檔案名要和第一步中的 resource 屬性的值一緻
内容為:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path path="." name="download"/>
</paths>
三、根據機型的Android系統級别執行不同的安裝apk的代碼
注意,根據系統版本執行不同代碼,7.0以下調用7.0+的代碼會報錯,7.0+的調用7.0以下的會報錯。
if (file!=null){ // file 即 apk檔案
Intent intent = new Intent(Intent.ACTION_VIEW);
// 由于沒有在Activity環境下啟動Activity,設定下面的标簽
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if(Build.VERSION.SDK_INT>=24) { //判讀版本是否在7.0以上
//參數1 上下文, 參數2 Provider主機位址 和配置檔案中保持一緻 參數3 共享的檔案
Uri apkUri =
FileProvider.getUriForFile(context, "com.xxx.xxxxx.fileprovider", file);
//添加這一句表示對目标應用臨時授權該Uri所代表的檔案
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
}else{
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
}
context.startActivity(intent);
}
作者:聽着music睡
出處:http://www.cnblogs.com/xqxacm/
Android交流群:38197636
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。