Android 适配7.0及以上的安装更新

    近期准备给APP增加一个下载更新的功能,原以为很简单,自己测试也通过了,但是发给测试后,发现apk下载完成,安装的页面弹不出来,郁闷了。

    原来的方法是这么写的:

    /**
     * android1.x-6.x
     *
     * @param path 文件的路径
     */
    public void startInstall(Context context, String path) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(install);
    }

    检查了一圈发现是Android 7.0 增加的Provider的问题,不能使用文件的绝对路径,而是需要使用,通过provider获取到的Uri去安装,修改后的如下:

    /**
     * android o 以上
     * @param context
     * @param path
     */
    public void startInstallTest(Context context, String path) {
        Uri uri = FileProvider.getUriForFile(context.getApplicationContext(), "your provider authority", new File(path));
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        if (MIUIUtils.isMIUI()) {
            ComponentName companent = new ComponentName("com.miui.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
            intent.setComponent(companent);
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }

    以上发现在小米系统中无法做到弹出安装页面,但是别人的却是可以安装,通过打印系统日志发现,在ActivityManager日志中我少了一个小米专用的Component,于是经过判断加上,就可以了。

    完整调用如下:

private void checkInstall(String path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            startInstallTest(this, path);
        } else {
            startInstall(this, path);
        }
    }

    顺便把判断miui的工具类添加上:

public class MIUIUtils {
    // 检测MIUI
    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";

    public static boolean isMIUI() {
        Properties prop = new Properties();
        boolean isMIUI;
        try {
            prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        isMIUI = prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;

        return isMIUI;
    }
}

    以上就是我在开发 下载更新过程中的遇到的坑,有部分手机需要 先授权,需要添加预处理才行,不过我没遇到这类机型,所以不再此次讨论范围,此外附上下载apk包的工具类

猜你喜欢

转载自blog.csdn.net/HeartCircle/article/details/107014520
今日推荐