首页 > 代码库 > Android下实现静默安装指定APK

Android下实现静默安装指定APK

什么是静默安装?既是可以在不提示用户的情况下,进行APK的安装。

有的时候,根据业务需求,需要实现静默安装APK,但是Android提供的安装接口是需要提示用户的前提下安装。

以下提供一个静默安装的解决方案(通过执行命令行的方式实现,需ROOT权限):

new Thread() {
    public void run() {
    Process process = null;
    OutputStream out = null;
    InputStream in = null;
    try {
    // 请求root
    process = Runtime.getRuntime().exec("su");
    out = process.getOutputStream();
    // 调用pm命令安装,理论上是可以做任何事情
    out.write(("pm install -r " + currentTempFilePath + "\n").getBytes());
    in = process.getInputStream();
    int len = 0;
    byte[] bs = new byte[1024];
    while (-1 != (len = in.read(bs))) {
    String state = new String(bs, 0, len);
    if (state.equals("Success\n")) {
       //安装成功后的操作
         }
       }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  }
}.start();