Android How to - Install and uninstall APK Silently








Question

We would like to know how to install and uninstall APK Silently.

Answer

/*from   ww  w. ja  v a  2 s .co  m*/
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import android.content.Intent;
import android.net.Uri;

class ApkUtil {

  public static boolean isRoot() {
    boolean flag = false;

    try {
      if ((!new File("/system/bin/su").exists())
          && (!new File("/system/xbin/su").exists())) {
        flag = false;
      } else {
        flag = true;
      }
    } catch (Exception e) {

    }
    return flag;
  }

  public static Intent getApkFileIntent(File file) {
    Intent intent = new Intent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(android.content.Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file),
        "application/vnd.android.package-archive");
    return intent;
  }

  public static boolean slientInstall(File file) {
    if (file == null) {
      return true;
    }
    boolean result = false;
    Process process = null;
    OutputStream out = null;
    try {
      process = Runtime.getRuntime().exec("su");
      out = process.getOutputStream();
      DataOutputStream dataOutputStream = new DataOutputStream(out);
      // dataOutputStream.writeBytes("chmod 777 " + file.getPath() + "\n");
      dataOutputStream
          .writeBytes("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install -r "
              + file.getPath());

      dataOutputStream.flush();

      dataOutputStream.close();
      out.close();
      int value = process.waitFor();

      if (value == 0) {
        result = true;
      } else if (value == 1) {
        result = false;
      } else {
        result = false;
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return result;
  }
  public static boolean slientUnInstall(String packagename) {
    boolean result = false;
    Process process = null;
    OutputStream out = null;
    try {
      process = Runtime.getRuntime().exec("su");
      out = process.getOutputStream();
      DataOutputStream dataOutputStream = new DataOutputStream(out);
      dataOutputStream
          .writeBytes("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm uninstall  "
              + packagename);
      dataOutputStream.flush();
      dataOutputStream.close();
      out.close();
      int value = process.waitFor();
      if (value == 0) {
        result = true;
      } else if (value == 1) {
        result = false;
      } else {
        result = false;
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return result;
  }
}