首先是前置准备工作,基本和7.0一样,在清单文件中申明
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
接着在values中增加一个file-path.xml文件
<paths>
<root-path path="" name="cjkt" />
<external-path path="Android/data/${applicationId}/" name="files_root" />
<external-path path="." name="external_storage_root" />
</paths>
这一步的目的是将真实路径转换成自定义的名字,规则如下:图表引用:Android O(Android 8.0)应用内安装正确姿势
子节点 | 对应路径 |
---|---|
root-path | . |
files-path | Context.getFilesDir() |
cache-path | Context.getCacheDir() |
external-path | Environment.getExternalStorageDirectory() |
external-files-path | Context.getExternalFilesDir(null) |
external-cache-path | Context.getExternalCacheDir() |
最后是8.0中遇到的问题,调不出安装界面,闪退了,看了log是权限问题,在Android 8.0的系统中,允许位置来源”应用的开关被移除,只能每次安装时手动授予“允许安装未知应用”的许可,解决方法加上这个权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
这几步做好就可以调用安装界面了
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName(), apkFile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
context.startActivity(intent);
}