系统级app需要实现静默安装apk的功能,且能兼容各安卓系统版本
废话不多说,直接上代码:
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
try {
//-i 指定安装程序包名称 , -r 覆盖安装 -d 阶级安装
process = new ProcessBuilder("pm", "install", "-i", context.getPackageName(), "-r", "-d", path).start();
successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line;
while ((line = successResult.readLine()) != null) {
successMsg.append(line);//.append("\n")
}
while ((line = errorResult.readLine()) != null) {
errorMsg.append(line);
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
if (process != null) {
process.destroy();
}
} catch (Throwable e) { }
}
Log.d(TAG, "installApk--- apk安装结果 suclog=" + successMsg+", error="+errorMsg);//installApk--- suclog:Success
if (!TextUtils.isEmpty(successMsg.toString()) && successMsg.toString().toLowerCase().contains("success")){
//安装成功
if (installListener != null){
installListener.installResutl(true, successMsg.toString());
}
}else{
//安装失败
if (installListener != null){
installListener.installResutl(false, errorMsg.toString());
}
}