Android 自动更新适配高低版本
2019-05-09 本文已影响0人
逆行的小电驴
- 安装APK部分代码
public static void installAPK(Activity activity, String 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) {
// 版本大于 N ,开始使用 fileProvider 进行安装
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(
activity
, activity.getPackageName() + ".provider"
, apkFile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
// 正常进行安装
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
}
activity.startActivity(intent);
}
- res/xml下新建provider_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>
- AndroidManifest.xml文件application节点下增加
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
- 当然最重要的权限不能忘记加
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
- 注意AndroidManifest.xml下的android:authorities="${applicationId}.provider"的provider要与installAPK方法内部的activity.getPackageName() + ".provider"中的provider名称一致
- 这样就可以不区分安卓版本,进行更新啦