Android应用内安装

Android应用内安装

    public static void installApk(Activity context, String filePath, int requestCode) {
        Log.e("TAG", "install apk" + filePath);
        if (TextUtils.isEmpty(filePath)) {
            Toast.makeText(context, "安装路径出错", Toast.LENGTH_SHORT).show();
            return;
        }
        File file = new File(filePath);
        Uri uri = Uri.fromFile(file);
        if (uri == null) {
            throw new RuntimeException("安装路径不正确");
        }

        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context, "com.zh.appinfotest.fileprovider", file);
        }

        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT < 14) {
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else if (Build.VERSION.SDK_INT < 16) {
            intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
            intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
            intent.putExtra(Intent.EXTRA_ALLOW_REPLACE, true);
        } else if (Build.VERSION.SDK_INT < 24) {
            intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
            intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
            intent.putExtra(Intent.EXTRA_ALLOW_REPLACE, true);
        } else {
            intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
            intent.setData(uri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
            intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
            intent.putExtra(Intent.EXTRA_ALLOW_REPLACE, true);
        }
        try {
            context.startActivityForResult(intent, requestCode);
        } catch (Exception e) {
            Log.e("TAG", e.getMessage());
        }
    }

上述代码是封装的安装app的方法。

其中需要注意的地方:

1:定义fileprovider

上一篇:VS Qt项目与QtCreator项目相互转换的方法


下一篇:Nginx多虚拟主机