安装软件Android

缘由

很多时候我们都需要给应用添加更新的功能,当我们下载完了安装包了,肯定是希望能够自动安装新版本的。但是由于安卓系统的限制,我们没法做到无感知的安装,所以就需要使用系统的软件安装器让用户去安装了。

代码

/**
 * 安装apk文件
 *
 * @param apkFile 安装包所在目录
 */
public static void installApk(Context context, File apkFile) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    try {
        String[] command = {"chmod", "777", apkFile.toString()};
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.start();
    } catch (IOException ignored) {
    }

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri contentUri = FileProvider.getUriForFile(context,
                context.getApplicationContext().getPackageName() + ".provider", apkFile);
        intent.setDataAndType(contentUri, context.getContentResolver().getType(contentUri));
    } else {
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    context.startActivity(intent);
    //关闭旧版本的应用程序的进程
    android.os.Process.killProcess(android.os.Process.myPid());
}
Search by:GoogleBingBaidu