对于签名相同的新旧版本apk,在更新的时候直接安装覆盖掉旧版本:
/**
* 静默安装
*
* @param apkPath
*/
public static String clientInstallApp(String apkPath) {
String result = "";
if (TextUtils.isEmpty(apkPath)) {
return result;
}
chmod("777", apkPath);
String[] args = { "pm", "install", "-r", apkPath };
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = null;
InputStream errIs = null;
InputStream inIs = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read = -1;
process = processBuilder.start();
errIs = process.getErrorStream();
while ((read = errIs.read()) != -1) {
baos.write(read);
}
baos.write("/n".getBytes());
inIs = process.getInputStream();
while ((read = inIs.read()) != -1) {
baos.write(read);
}
byte[] data = baos.toByteArray();
result = new String(data);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (errIs != null) {
errIs.close();
}
if (inIs != null) {
inIs.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
return result;
}
当新版本和旧版本apk的签名不一样的时候,实现代码如下 :
/**
* 静默卸载和安装
*
* @param packageName
*/
public static String clienUpdate(String... command) {
Process process = null;
InputStream errIs = null;
InputStream inIs = null;
String result = "";
try {
process = new ProcessBuilder().command(command).start();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read = -1;
errIs = process.getErrorStream();
while ((read = errIs.read()) != -1) {
baos.write(read);
}
inIs = process.getInputStream();
while ((read = inIs.read()) != -1) {
baos.write(read);
}
result = new String(baos.toByteArray());
if (inIs != null)
inIs.close();
if (errIs != null)
errIs.close();
process.destroy();
} catch (IOException e) {
result = e.getMessage();
}
return result;
}
卸载方法;
clienUpdate(“pm”,”uninstall”, packageName);//卸载apk,packageName为包名
必须先卸载,才能安装新版本
安装方法:
clienUpdate(“pm”,”install”,”-f”,filePath);//安装apk,filePath为apk文件路径
其他配置:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.demo.service"
android:installLocation="internalOnly"
android:sharedUserId="android.uid.system"//需要添加此配置
android:versionCode="38"
android:versionName="1.0.33" >
权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.DELETE_PACKAGES" />
<uses-permission android:name="android.permission.CLEAR_APP_CACHE" />
<uses-permission android:name="android.permission.CLEAR_APP_USER_DATA" />
如有必要请加上其他相关权限!!!