Android7.0以上自动更新安装apk

来源:互联网 发布:windows常见界面开发 编辑:程序博客网 时间:2024/05/18 02:23

Android7.0以上加了很多特性,也对系统做了很多的优化和升级,而在对Uri的访问上也做了改变,以下用安装apk的例子来说明

对于程序,我们要实现程序能够自动检查更新安装,我们需要给程序赋予权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

以上这是第一步,接着,我们需要在Manifest.xml文件当中做如下配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.test">...    
<application        ...>        <provider            android:name="android.support.v4.content.FileProvider"            android:authorities="com.test.fileprovider"            android:exported="false"            android:grantUriPermissions="true">            <meta-data                android:name="android.support.FILE_PROVIDER_PATHS"                android:resource="@xml/file_paths" />        </provider>        ...    </application></manifest>
主要添加的 就是provider标签部分,对于属性android:authorities一定要注意,当中的前面部分,com.test是程序的appId,就是applicationId,在build.gradle文件当中可以看到。
上面配置当中是否有看到android:resource="@xml/file_paths"呢,这里再来说一下xml下的file_paths
在项目中的res下新建xml目录,并在xml目录当中新建file_paths.xml文件,该文件当中的内容如下:
<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android">    <external-path        name="external_files"        path="" /></paths>
其实,我的path为空则表示为Environment.getExternalStorageDirectory()的主目录;好了,到此为止将配置做好了,以下是调用程序的安装功能,代码如下:
Intent intent = new Intent();        //执行动作        intent.setAction(Intent.ACTION_VIEW);        //判读版本是否在7.0以上        if (Build.VERSION.SDK_INT >= 24) {            Uri apkUri = FileProvider.getUriForFile(mContext, "com.test.fileprovider", file);            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");        } else {            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");        }        mContext.startActivity(intent);
关于file_paths的其实配置有其他文章参考,原文地址为:http://www.czhzero.com/2016/12/21/how-to-install-apk-on-Android7-0/