private void install(String filePath) { Log.i(TAG, "開始執(zhí)行安裝: " + filePath); File apkFile = new File(filePath); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Log.w(TAG, "版本大于 N ,開始使用 fileProvider 進(jìn)行安裝"); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri contentUri = FileProvider.getUriForFile( mContext , "你的包名.fileprovider" , apkFile); intent.setDataAndType(contentUri, "application/vnd.android.package-archive"); } else { Log.w(TAG, "正常進(jìn)行安裝"); intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); } startActivity(intent); }
關(guān)于在代碼中安裝 APK 文件,在 Android N 以后,為了安卓系統(tǒng)為了安全考慮,不能直接訪問軟件,需要使用 fileprovider 機(jī)制來訪問、打開 APK 文件。
上面的 if 語句,就是區(qū)分軟件運(yùn)行平臺(tái),來對(duì) intent 設(shè)置不同的屬性。
在清單文件(manifests.xml)application 標(biāo)簽中增加 <provider> 標(biāo)簽:
<application> <!--其他的配置項(xiàng)--> <provider android:name="android.support.v4.content.FileProvider" android:authorities="你的包名.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider> <!--其他的配置項(xiàng)--> </application>
注意兩點(diǎn)內(nèi)容:
1. android:authorities="你的包名.fileprovider" 這個(gè)屬性要設(shè)置成你自己的包名。
2. <meta-data> 標(biāo)簽下 android:resource="@xml/file_paths" 是要配置的 xml 文件,他的內(nèi)容如下:
在 res/xml 下增加文件: file_paths.xml 該文件內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?><paths> <external-path name="your_name" path="your_path" /></paths>
上面的兩個(gè)屬性要根據(jù)自己的使用來配置。
其中 <external-path> 就是手機(jī)的外置存儲(chǔ)目錄。
在 Java 代碼中使用最上面的代碼,問題解決。
這里面有個(gè)要注意的點(diǎn):
清單文件中的 android:authorities="你的包名.fileprovider" 和 JAVA 代碼中:
Uri contentUri = FileProvider.getUriForFile( mContext , "你的包名.fileprovider" , apkFile);
中綠色背景的字段必須一致,否則會(huì)報(bào)錯(cuò)。
聯(lián)系客服