打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Android 在代码中安装 APK 文件

 http://www.cnblogs.com/newjeremy/p/7294519.html

话不说,上代码

    private void install(String filePath) {        Log.i(TAG, "开始执行安装: " + 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 进行安装");            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, "正常进行安装");            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");        }        startActivity(intent);    }

 代码说明

关于在代码中安装 APK 文件,在 Android N 以后,为了安卓系统为了安全考虑,不能直接访问软件,需要使用 fileprovider 机制来访问、打开 APK 文件。

上面的 if 语句,就是区分软件运行平台,来对 intent 设置不同的属性。

适配 Android 各个版本,使用代码安装 APK

第一步:

在清单文件(manifests.xml)application 标签中增加 <provider> 标签:

    <application>        <!--其他的配置项-->        <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>        <!--其他的配置项-->    </application>    

注意两点内容:

1. android:authorities="你的包名.fileprovider" 这个属性要设置成你自己的包名。

2. <meta-data> 标签下 android:resource="@xml/file_paths" 是要配置的 xml 文件,他的内容如下:

第二步:

在 res/xml 下增加文件: file_paths.xml 该文件内容如下:

<?xml version="1.0" encoding="utf-8"?><paths>    <external-path        name="your_name"        path="your_path" /></paths>

上面的两个属性要根据自己的使用来配置。

其中 <external-path> 就是手机的外置存储目录。

第三步:

在 Java 代码中使用最上面的代码,问题解决。

这里面有个要注意的点:

清单文件中的 android:authorities="你的包名.fileprovider" 和 JAVA 代码中:

Uri contentUri = FileProvider.getUriForFile(                    mContext                    , "你的包名.fileprovider"                    , apkFile);

绿色背景的字段必须一致,否则会报错。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
解决 Android N 7.0 上 报错:android.os.FileUriExposedExc...
Android 7.0文件共享
Android FileProvider 属性配置详解及FileProvider多节点问题
Android 7.0调用相机拍照,返回后显示拍照照片
代码运行apk文件,程序更新安装
Content Provider(二)之 FileProvider 实现应用文件共享
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服