1:新建一个类,继承FilePrivoder,什么都不用重写,主要市避免和其他引用第三方配置的FilePrivoder冲突
import androidx.core.content.FileProvider;
/**
* @author wangyn
* @date 2020/8/5 8:58
* Description: 作用描述 app 版本升级 主要用于区分不同的FileProvider,避免FileProvider
*/
public class VersionUpgradeFileProvider extends FileProvider {
}
2:在清单文件配置该VersionUpgradeFileProvider
<!-- app 升级配置用 VersionUpgradeFileProvider -->
<provider
android:name=".utils.VersionUpgradeFileProvider"
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>
3:然后在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="external_storage_root"
path="." />
</paths>
4:请求服务器接口,判断当前运行的版本号和服务器的版本号大小,小于就是有新版本,提示用户升级去,可以直接挂在后台,或是直接开启线程下载就行,下载这块因为涉及好几块UI就不贴了,就一普通的下载,进度回调,
5:当apk 下载完成后进行安装操作,主要代码如下:
//apk:下载好的apk文件
private static void actionInstallApk(File apk, Context context) {
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", apk);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//注意:是addFlags() 不能是setFlags(),会覆盖掉Intent.FLAG_ACTIVITY_NEW_TASK ,不然安装完成不显示完成打开页面
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
}
context.startActivity(intent);
}
注意:读写权限以及Android10 权限的变更,我是直接在清单文件做了配置,