不能自动更新安装apk是什么原因
原因就是android6.0以下
解决,android7.0以上才能自动更新安装apk
步骤:
第一步骤,添加依赖包一句:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
第二步骤,在AndroidManifest.xml里的application下面添加provider:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo.test">
...
<application
...>
<!-- ===========添加=========== -->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.demo.test.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
主要添加的,就是provider标签部分,对于属性android:authorities一定要注意,当中的后面部分,com.demo.test是程序的appId,就是applicationId,在app的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()的主目录;好了,到此为止将配置做好了,以下是调用程序的安装功能,代码如下:
/**
* 安装apk
*/
protected void installApk(File file) {
Intent intent = new Intent();
//执行动作
intent.setAction(Intent.ACTION_VIEW);
//****新增代码****
//判读版本是否在7.0以上
if (Build.VERSION.SDK_INT >= 24) {
Uri apkUri = FileProvider.getUriForFile(MainActivity.this, "com.demo.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");
}
startActivity(intent);
}
自动更新安装apk如下图: