Android: Java code for normal installation and installation of apps, and Silent Installation and uninstallation of Android apps
Differences
- After you perform normal installation and uninstallation, a prompt box is displayed, which is the same as opening the APK file in the File Manager for installation and uninstallation.
- Perform Silent Installation and uninstallation. Normally, the foreground will not respond, and the APP will be installed and uninstalled in the background. This function is also called "background installation". To achieve this function, you need to ROOT.
Normal Installation
Core code:
Intent intent = new Intent(Intent.ACTION_VIEW);intent.setDataAndType( Uri.fromFile(new File(apkPath)), "application/vnd.android.package-archive");context.startActivity(intent);
Normal uninstall
Core code:
Uri packageURI = Uri.parse("package:" + packageName);Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);context.startActivity(intent);
In the above Code, packageName is the package name of the target APP.
Silent Installation
Core code:
private static final String SILENT_INSTALL_CMD = "pm install -r ";
String installCmd = SILENT_INSTALL_CMD + apkPath; // The PM command does not support Chinese int result =-1; DataOutputStream dos = null; Process process = null; try {process = runtime.getruntime(cmd.exe c ("su"); dos = new DataOutputStream (process. getOutputStream (); dos. writeBytes (installCmd + "\ n"); dos. flush (); dos. writeBytes ("exit \ n"); dos. flush (); process. waitFor (); result = process. exitValue ();} catch (Exception e) {e. printSta CkTrace ();} finally {try {if (dos! = Null) {dos. close () ;}if (process! = Null) {process. destroy () ;}} catch (IOException e) {e. printStackTrace () ;}} return result;
Silent uninstall
Core code:
// If you want to retain data, you need to add the-k parameter, but the uninstallation will not be completely private static final String SILENT_UNINSTALL_CMD = "pm uninstall ";
String uninstallCmd = SILENT_UNINSTALL_CMD + appPackageName;int result = -1;DataOutputStream dos = null;Process process = null;try { process = Runtime.getRuntime().exec("su"); dos = new DataOutputStream(process.getOutputStream()); dos.writeBytes(uninstallCmd + "\n"); dos.flush(); dos.writeBytes("exit\n"); dos.flush(); process.waitFor(); result = process.exitValue();} catch (Exception e) { e.printStackTrace();} finally { try { if(dos != null) { dos.close(); } if(process != null){ process.destroy(); } } catch (IOException e) { e.printStackTrace(); }}return result;
In the above Code, appPackageName is the package name of the target APP.
For more information, seeinstall
,uninstall
,silentInstall
AndsilentUninstall
These four methods.