How to Install or Uninstall An Android APK File Programmatically

By:   –  Last updated:   –  #android ·  #java

Code Theme [Dark]

Content Overview [Hide]

Sample codes to demonstrate how to programmatically install or uninstall an APK.

Android system provides a default application PackageInstaller to install or uninstall an APK file.

You can see detail in PackageInstaller application's AndroidManifest.xml file on GitHub.

<!-- ... -->

<activity android:name=".PackageInstallerActivity"
          android:configChanges="orientation|keyboardHidden|screenSize"
          android:excludeFromRecents="true">
  <intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.INSTALL_PACKAGE" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="file" />
    <data android:scheme="content" />
    <data android:mimeType="application/vnd.android.package-archive" />
  </intent-filter>
  
  <!-- ... -->
</activity>

<!-- ... -->

<activity android:name=".UninstallerActivity"
          android:configChanges="orientation|keyboardHidden|screenSize"
          android:excludeFromRecents="true"
          android:theme="@style/Theme.AlertDialogActivity">
  <intent-filter android:priority="1">
    <action android:name="android.intent.action.DELETE" />
    <action android:name="android.intent.action.UNINSTALL_PACKAGE" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:scheme="package" />
  </intent-filter>
</activity>

<!-- ... -->

1 Installing an APK using Android PackageInstaller

The PackageInstallerActivity is the default system package installer Activity. It can be launched using an implicit intent.

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

import java.io.File;

/**
  * Install APK using PackageInstaller
  * @param apkFile  File object of APK
  */
private void installAPK(File apkFile) {
    Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
    startActivity(intent);
}

2 Uninstalling an APK using Android PackageInstaller

Similarly, an installed APK can be uninstalled programmatically.

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

/**
  * Uninstall APK using PackageInstaller
  * @param apkPackageName
  */
private void uninstallAPK(String apkPackageName) {
    Intent intent = new Intent("android.intent.action.DELETE");
    intent.setData(Uri.parse("package:" + apkPackageName));
    startActivity(intent);
}