Android 静默安装

259 阅读1分钟

静默安装

***First blood *** 遇到了静默安装需求,普通的手机是需要root权限的,root后即可以使用pm命令安装,也可以签名为系统应用后即可使用pm命令静默安装,系统签名命令如下:

set apkFile=%1
set signedFile=%apkFile%_signed.apk
java -jar signapk.jar platform.x509.pem platform.pk8 %apkFile% %signedFile%

这段命令可直接在windows下存储为bat下次直接把文件拖入即可签名 需要的文件:signapk.jar,platform.x509.pem,platform.pk8 下载链接 注:看手机型号而定,国内的手机型号比较ken...

在网上找了下资料,记录如下:

具体实现

static  DataOutputStream dataOutputStream = null; 
static BufferedReader errorStream = null; 
static Process process;
static boolean result = false;
public static  boolean slientInstall(String apkPath)
{  
  try {        
process = Runtime.getRuntime().exec("su"); //获取su权限
 dataOutputStream = new DataOutputStream(process.getOutputStream());//获取
      String command = "pm install -r "+apkPath+"\n"; //安装命令
 String path = apkPath;       
 Log.e("Tag",command);       
 Log.e("Tag",path+"+++>path");       
     dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));        
     dataOutputStream.flush();     
     dataOutputStream.writeBytes("exit\n");       
     dataOutputStream.flush();       
   try {            
  process.waitFor();           
   errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream())); //记录安装的信息      
 String msg = "";
  String line;           
 while ((line = errorStream.readLine())!= null)
{               
 msg+=line;          
  }          
  Log.e("Tag","安装的信息是"+msg);   
         if (!msg.contains("Failure"))
                    {
                    return true;           
                     }       
                                              } 
catch (InterruptedException e)
 {           
 e.printStackTrace();       
 }   
 }
 catch (IOException e) 
{        
e.printStackTrace(); 
   }finally {  
          try {             
   if (dataOutputStream!=null){    
            dataOutputStream.close();   
             }             
   if (errorStream!= null){      
              errorStream.close();      
          }        
    } catch (IOException e) {  
              e.printStackTrace();  
          }   
 }    
return result;
}

上面就实现了静默安装的功能. 记得加上权限:

<uses-permission android:name="android.permission.INSTALL_PACKAGES" />

###作者 fuyifang