使用pm命令实现静默安装
一.系统签名
1.通过系统中的签名文件,使用命令签名
java -jar signapk.jar platform.x509.pem platform.pk8 app.apk app_signed.apk
2.利用系统中的签名文件生成xxx…keystore,在AS里签名
3.通过ubuntu环境编译,mk文件中设置
LOCAL_CERTIFICATE := platform
out中编译出来的应用就是系统签名后的
具体签名步骤可以参考
二.在AndroidManife.xml 中添加android:sharedUser
android:sharedUserId="android.uid.system"
三.安装的方法
private static String TAG = "MainActivity";
private File fileDownloads;
private File imageFileDirctory;
private String path;
//安装文件路径 注意FileProvider的使用
//可以参考https://www.jianshu.com/p/47fcd7873f39
private void init() {
try {
fileDownloads = this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
imageFileDirctory = new File(fileDownloads + "/" + "CPU-Z.apk");
path = imageFileDirctory.getAbsolutePath();
//storage/emulated/0/Android/data/com.fih.storeapp/files/Download/CPU-Z.apk
Log.e(TAG, path);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
public static int installSilent(String filePath) {
File file = new File(filePath);
if (filePath == null || filePath.length() == 0 || file == null || file.length() <= 0 || !file.exists() || !file.isFile()) {
return 1;
}
//pm install -i 'com.fih.mypjdemo' --user 0
//com.fih.app是当前应用的包名,不是安装的包名
String[] args = {"pm", "install", "-i", "com.fih.app", "--user", "0", filePath};
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = new StringBuilder();
StringBuilder errorMsg = new StringBuilder();
int result;
try {
process = processBuilder.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 (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (successResult != null) {
successResult.close();
}
if (errorResult != null) {
errorResult.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
// TODO should add memory is not enough here
if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
result = 0;
} else {
result = 2;
}
Log.e(TAG, "successMsg:" + successMsg + ", ErrorMsg:" + errorMsg);
return result;
}