Android笔记之利用系统权限下命令安装apk

来源:互联网 发布:《疯狂java讲义》 编辑:程序博客网 时间:2024/06/05 00:29

我们在定制Android系统的时候,应用商店是很重要的部分,市面上大部分的应用商店都采用了静默安装的方式来安装升级应用,这是怎么做到的呢?两点:
1.具有系统权限
2.使用pm install来安装

    /**      * 静默安装的实现类,调用install()方法执行具体的静默安装逻辑。      */      public class SilentInstall {          /**          * 执行具体的静默安装逻辑,需要手机ROOT。          * @param apkPath 要安装的apk文件的路径          * @return 安装成功返回true,安装失败返回false。          */          public boolean install(String apkPath) {              boolean result = false;              DataOutputStream dataOutputStream = null;              BufferedReader errorStream = null;              try {                  // 申请su权限                  Process process = Runtime.getRuntime().exec("su");                  dataOutputStream = new DataOutputStream(process.getOutputStream());                  // 执行pm install命令                  String command = "pm install -r " + apkPath + "\n";                  dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));                  dataOutputStream.flush();                  dataOutputStream.writeBytes("exit\n");                  dataOutputStream.flush();                  process.waitFor();                  errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));                  String msg = "";                  String line;                  // 读取命令的执行结果                  while ((line = errorStream.readLine()) != null) {                      msg += line;                  }                  Log.d("TAG", "install msg is " + msg);                  // 如果执行结果中包含Failure字样就认为是安装失败,否则就认为安装成功                  if (!msg.contains("Failure")) {                      result = true;                  }              } catch (Exception e) {                  Log.e("TAG", e.getMessage(), e);              } finally {                  try {                      if (dataOutputStream != null) {                          dataOutputStream.close();                      }                      if (errorStream != null) {                          errorStream.close();                      }                  } catch (IOException e) {                      Log.e("TAG", e.getMessage(), e);                  }              }              return result;          }      }  
1 0
原创粉丝点击