本文主要是介绍Android7.0系统使用Intent跳转到APK安装页,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
报错 android.os.FileUriExposedException:
原因
Android N对访问文件权限收回,按照Android N的要求,若要在应用间共享文件,您应发送一项 content://URI,并授予 URI 临时访问权限。
而进行此授权的最简单方式是使用 FileProvider类。
解决方法
1.在manifest中注册FileProvider
<providerandroid:name="android.support.v4.content.FileProvider"android:authorities="${applicationId}.provider"android:exported="false"android:grantUriPermissions="true"></provider>
2、指定可用的文件路径
在项目的res目录下,创建xml文件夹,并新建一个file_paths.xml文件。通过这个文件来指定文件路径:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android"><files-path name="tangdada" path="download/" /><external-path name="tangdada" path="download/" />
</paths>
有多种指定路径,在<paths>标签内应至少包含一种,或者多种。
a、表示应用程序内部存储区中的文件/子目录中的文件
<files-path name="name" path="image" />
等同于Context.getFileDir() : /data/data/com.xxx.app/files/image
b、表示应用程序内部存储区缓存子目录中的文件
<cache-path name="name" path="image" />
等同于Context.getCacheDir() : /data/data/com.xxx.app/cache/image
c、表示外部存储区根目录中的文件
<external-path name="name" path="image" />
等同于Environment.getExternalStorageDirectory() : /storage/emulated/image
d、表示应用程序外部存储区根目录中的文件
<external-files-path name="name" path="image" />
等同于Context.getExternalFilesDir(String) / Context.getExternalFilesDir(null) : /storage/emulated/0/Android/data/com.xxx.app/files/image
e、表示应用程序外部缓存区根目录中的文件
<external-cache-path name="name" path="image" />
等同于Context.getExternalCacheDir() : /storage/emulated/0/Android/data/com.xxx.app/cache/image
3、引用指定的路径
在刚才Androidmanifest.xml中声明的provider进行关联:
<providerandroid:name="android.support.v4.content.FileProvider"android:authorities="${applicationId}.provider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/file_paths" />
</provider>
所以最终安装apk的方法可以这么写了:
File apkfile = new File(mSavePath, mPackageNameString);if (!apkfile.exists()) {return;}Intent i = new Intent(Intent.ACTION_VIEW);if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本Uri apkUri = getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", apkfile); //与manifest中定义的provider中的authorities="com.xinchuang.buynow.fileprovider"保持一致i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);i.setDataAndType(apkUri, "application/vnd.android.package-archive");i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);} else {i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);i.setDataAndType(Uri.parse("file://" + apkfile.toString()),"application/vnd.android.package-archive");}mContext.startActivity(i);
}
在网上找了好多方法 最后参考stackoverflow里面的才最终解决
附上stackoverflow链接
这篇关于Android7.0系统使用Intent跳转到APK安装页的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!