1、普通模式安装,调用系统Intent,代码如下:
public void install(Context context, String filePath) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + filePath),
"application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
2、静默安装
(1)、静默安装需要系统应用安装权限,需要在AndroidManifest.xml中添加:
a.)安装权限:
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
b.) 系统权限:
android:sharedUserId="android.uid.system"
(2)、实现代码
静默安装代码如下,实际是通过pm install -r 命令安装。
注意:该函数最好在新建的线程中运行并通过handler发送安装结果给主线程,否则安装时间较长会导致ANR。
public String install(String apkAbsolutePath){
String[] args = { "pm", "install", "-r", apkAbsolutePath };
String result = "";
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;
}
3,使用系统sign key进行签名后安装,或者push到/system/app/下面。