Android 静默安装应用和静默卸载应用

2018-03-01 11:11:50来源:https://www.jianshu.com/p/e1905765964d作者:叶应是叶人点击

分享


这里提供两个Android系统下静默安装应用和静默卸载应用的方法,在 5.1 版本系统上运行通过。当然,运行代码的应用需要有系统权限,这就需要应用通过系统签名文件进行签名了,需要使用到 platform.pk8 和 platform.x509.pem 两个文件,可以参照我的另一篇文章:Android 用 platform.pk8 和 platform.x509.pem 生成 keystore 系统签名文件


   /**
* 静默安装App
*
* @param apkPath apk路径
* @return 是否安装成功
*/
public static boolean installApp(String apkPath) {
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
try {
process = new ProcessBuilder("pm", "install", "-r", apkPath).start();
successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
} catch (Exception e) {
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (Exception e) {
}
if (process != null) {
process.destroy();
}
}
//如果含有“success”单词则认为安装成功
return successMsg.toString().equalsIgnoreCase("success");
}
/**
* 静默卸载App
*
* @param packageName 包名
* @return 是否卸载成功
*/
public static boolean uninstallApp(String packageName) {
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
try {
process = new ProcessBuilder("pm", "uninstall", packageName).start();
successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while ((s = successResult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
} catch (Exception e) {
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (Exception e) {
}
if (process != null) {
process.destroy();
}
}
//如果含有“success”单词则认为卸载成功
return successMsg.toString().equalsIgnoreCase("success");
}
/**
* 判断应用是否存在
*
* @param context 上下文
* @param packageName 包名
* @return 是否存在
*/
private boolean appExist(Context context, String packageName) {
try {
List<PackageInfo> packageInfoList = context.getPackageManager().getInstalledPackages(0);
for (PackageInfo packageInfo : packageInfoList) {
if (packageInfo.packageName.equalsIgnoreCase(packageName)) {
return true;
}
}
} catch (Exception e) {
}
return false;
}







最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台