Android 7.0 apk安装

简介

Android 7.0开始,系统修改了安全机制:
限定应用在默认情况下只能访问自身应用数据。所以当我们想通过File对象访问其它package数据时,就需要借助于ContentProvider、FileProvider这些组件,否则会报FileUriExposedException异常。
由此,当我们在app内想要访问SD卡download目录下的apk文件就会报错。这里需要借助FileProvider对公共目录申请权限。

代码实现

首先需要在Manifest的application标签下添加FileProvider的声明:

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

配置file_paths.xml文件:

目录截图
      <?xml version="1.0" encoding="utf-8"?>
      <paths>
            <external-path path="." name="external_storage_root" />
            <external-path name="external_storage_root" path="."/>
            <files-path name="files" path="."/>
            <external-path
                  name="download"
                  path="" />
            <external-files-path
                  name="Download"
                  path="" />
    </paths>

安装apk的相关代码:

     //判断是否是AndroidN以及更高的版本
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        Uri contentUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + "" +
                                ".fileProvider", new File(Uri.parse(getLatestBackendDownloadPkgUri()).getPath()));
                        installIntent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        installIntent.setDataAndType(Uri.parse(getLatestBackendDownloadPkgUri()),
                                "application/vnd.android.package-archive");
                        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    }
                    mContext.startActivity(installIntent);
                }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容