apk 静默安装

如果需要应用进行静默安装,则需要满足一下两个条件
1  必须添加权限 <uses-permission android:name="android.permission.INSTALL_PACKAGES" />
2  必须是系统应用,或者系统签名应用

 

方法 1 通过 adb install 安装

/**
 *
 * @param apkFilePath 安装包路径
 * @return true 、false
 */
  public boolean installByADB(String apkFilePath){
    boolean success = false;
    if (apkFilePath == null || apkFilePath.equals("")) {return success;}
    File apkFile = new File(apkFilePath);
    if (!apkFile.exists() || apkFile.isDirectory()) {return success;}
    String[] args = { "pm", "install", "-r", "-d", apkFilePath };
    ByteArrayOutputStream eBAout = new ByteArrayOutputStream();
    ByteArrayOutputStream nBAout = new ByteArrayOutputStream();
    ProcessBuilder processBuilder = null;
    java.lang.Process process = null;
    InputStream eis = null;
    InputStream is = null;
    int num = 0;
    byte[] buffer = new byte[1024];
    try {
      processBuilder = new ProcessBuilder(args);
      process = processBuilder.start();
      eis = process.getErrorStream();
      while ((num = eis.read(buffer)) != -1) {
        eBAout.write(buffer, 0, num);
      }
      is = process.getInputStream();
      while ((num = is.read(buffer)) != -1) {
        nBAout.write(buffer, 0, num);
      }
      String error = eBAout.toString("UTF-8");
      String normal = nBAout.toString("UTF-8");
      if(normal != null && normal.contains("Success")){success = true;}
    } catch (IOException e) {
    } catch (Exception e) {
    } catch (Throwable t) {
    } finally {
      try {
        if (null != eis) {eis.close();}
      } catch (Exception e) {}
      try {
        if (null != is) {is.close();}
      } catch (Exception e) {}
        process.destroy();
      }
      return success;
   }

 方法2 通过PM安装
 这个方法的前提是将framework参与编译并排列第一

/**
 * @param context
 * @param apkPath
 */
public void installSilentlyBYPM(Context context, String apkPath) {
    if(apkPath == null || "".equals(apkPath)){return;}
    File apkFile = new File(apkPath);
    (!apkFile.exists() || apkFile.isDirectory()){return;}
    Uri apkPackageURI = Uri.fromFile(apkFile);
    int installFlags = PackageManager.INSTALL_ALL_USERS|PackageManager.INSTALL_REPLACE_EXISTING;
   PackageManager pm = context.getPackageManager();
   pm.installPackage(apkPackageURI, new PackageInstallObserver(){
           @Override
            public void onPackageInstalled(String basePackageName, int returnCode, String msg, Bundle extras){
                super.onPackageInstalled(basePackageName, returnCode, msg, extras);
                if(returnCode == 1){
                     //如果安装包的包名等于basePackageName; 则安装成功
                }
            }
        }, installFlags, context.getPackageName());
 }

 

posted @ 2017-07-03 21:18  欧颜柳  阅读(764)  评论(0编辑  收藏  举报