final String archiveFilePath = getInstallApkFullPath(); if (!(archiveFilePath == null)) { // 判断字符串是否为空要用==, 不要用equals方法 LogUtil.d(TAG, "run: start to install apk: " + archiveFilePath); // String[] args = {"pm", "install", "-r", archiveFilePath}; 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('*'); 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(); } } } else { LogUtil.d(TAG, "no apk need to install"); } }
private String getInstallApkFullPath() { String apkDirPath = Environment.getExternalStorageDirectory().getPath() + "/Download"; File apkFile = new File(apkDirPath); File[] apkFiles = apkFile.listFiles(); for (int i = 0; i < apkFiles.length; i++) { if (needUpdate(apkFiles[i].getAbsolutePath())) { LogUtil.d(TAG, "run: start to install apk: " + apkFiles[i].getAbsolutePath()); return apkFiles[i].getAbsolutePath(); } } return null; }