android调用安装和静默安装--要root权限

第一种是 通过Intent机制,调出系统安装应用,重新安装应用的话,会保留原应用的数据。

String fileName = Environment.getExternalStorageDirectory() + apkName;
 
Uri uri = Uri.fromFile(new File(fileName));
 
Intent intent = new Intent(Intent.ACTION_VIEW);
 
intent.setDataAndType(Uri, application/vnd.android.package-archive");
 
startActivity(intent);

第二种是静默安装

public static boolean installFile(File path) {
		boolean result = false;
		Process process = null;
		OutputStream out = null;
		InputStream in = null;
		String state = null;
		try {
			// 请求root
			process = Runtime.getRuntime().exec("su");
			out = process.getOutputStream();

			// 调用安装,将文件写入到process里面
			out.write(("pm install -r " + path + "\n").getBytes());

			// 这里拿到输出流,开始安装操作
			in = process.getInputStream();
			int len = 0;
			byte[] bs = new byte[256];
			while (-1 != (len = in.read(bs))) {
				state = new String(bs, 0, len);
				if (state.equals("Success\n")) {
					// 安装成功后的操作
					result = true;
					Log.e("成功", state);
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.flush();
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}


你可能感兴趣的:(android,安装APK,静默安装)