Android7.0后台服务器更新之后使用Intent跳转至APK安装页

来源:互联网 发布:3d展示软件 编辑:程序博客网 时间:2024/05/16 12:10

问题描述:华为荣耀8  Android7.0手机系统下载APK更新包之后未跳转至APK安装页,报 android.os.FileUriExposedException:(在相应的手机安装目录下能找apk文件)其他手机能正常跳转。


原因:Android N对访问权限收回,按照Android N的要求,若要在应用间共享文件,您应发送一项content://URI,并授予URI临时访问权限。因此进行此授权的最简单方式是使用FileProvider类。


解决方法

1.在AndroidManifest.xml中注册FileProvider。

<provider    android:name="android.support.v4.content.FileProvider"    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /></provider>

2.指定要访问的文件路径

   在项目的res目录下,创建xml文件夹,并创建一个新的file_paths.xml文件,通过这个文件来指定要访问的文件路径:

<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android">    <external-path name="name" path="download/apk"></external-path></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/0/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


最终实现APK安装的方法

   File file = new File(filepath);   if (!file.exists()) {      return;   }   Intent i = new Intent(Intent.ACTION_VIEW);
   i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
   //与manifest中定义的provider中的authorities="com.xinchuang.buynow.fileprovider"保持一致
  Uri apkUri = FileProvider.getUriForFile(context, ${applicationId} + ".fileprovider", var0); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); i.setDataAndType(apkUri, "application/vnd.android.package-archive"); } else { i.setDataAndType(Uri.fromFile(file)),"application/vnd.android.package-archive"); } mContext.startActivity(i);}
最后下载更新,实现页面成功跳转至安装页面。

附上stackoverflow链接






原创粉丝点击