其他分享
首页 > 其他分享> > Android应用内安装

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

标签:EXTRA,true,putExtra,uri,intent,应用,Intent,Android,安装
来源: https://blog.csdn.net/qq_23025319/article/details/119347503