Android 静默安装/后台安装

Android实现静默安装其实很简单,今天在网上找资料找半天都说的很复杂,什么需要系统安装权限、调用系统隐藏的api、需要系统环境下编译、需要跟systemUI同进程什么的。我不知道他们真的实现了静默安装没有,反正我按照他们的方式统统都失败了。
    下面我来说说我的静默安装实现方式,亲测效果跟豌豆荚一样,并且实现起来非常简单:
   
    1.支持静默安装的机器必须Root,这个不需要我多讲了。
    2.使用pm指令安装即可。
    3.特别注意 PM指令不支持中文,也就说路径中有中文会导致安装失败!

    关键代码如下:

execRootCmdSilent("pm install -r " + Environment.getExternalStorageDirectory().getPath()+"/xxx.apk")

public int execRootCmdSilent(String cmd) {  
       int result = -1;  
       DataOutputStream dos = null;  
  
       try {  
           Process p = Runtime.getRuntime().exec("su");  
           dos = new DataOutputStream(p.getOutputStream());  
  
           Log.i(TAG, cmd);  
           dos.writeBytes(cmd + "\n");  
           dos.flush();  
           dos.writeBytes("exit\n");  
           dos.flush();  
           p.waitFor();  
           result = p.exitValue();  
       } catch (Exception e) {  
           e.printStackTrace();  
       } finally {  
           if (dos != null) {  
               try {  
                   dos.close();  
               } catch (IOException e) {  
                   e.printStackTrace();  
               }  
           }  
       }  
       return result;  
   }

不需要在Manifest中声明任何权限

猜你喜欢

转载自iaiai.iteye.com/blog/2168811