美文网首页
Android 自动更新适配高低版本

Android 自动更新适配高低版本

作者: 逆行的小电驴 | 来源:发表于2019-05-09 14:22 被阅读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名称一致
  • 这样就可以不区分安卓版本,进行更新啦

相关文章

网友评论

      本文标题:Android 自动更新适配高低版本

      本文链接:https://www.haomeiwen.com/subject/cjewoqtx.html