Search code examples
androidinstallationandroid-package-managersactivity-managerandroid-activitymanager

Android: Install another app and detect when it is launched the first time


I have an application that installs other applications, just like Google Play Store. To complete the chain of analytics, I need to be able to detect when the apps installed are launched the first time.

Google Play Store definitely has it implemented in some way.


Solution

  • Android system does that for you. The package manager broadcasts Intent.ACTION_PACKAGE_FIRST_LAUNCH to the installer when an installed application is launched for the first time. To make sure you receive it, you need to:

    • Set the installer package name as soon as you install the application, as the broadcast is restricted to the installer package name set for the application being launched.

      getPackageManager().setInstallerPackageName("com.example", getApplicationContext().getPackageName());
      
    • Make sure you are not using PackageManager.INSTALL_REPLACE_EXISTING, as it will be assumed to be an update, for which the broadcast is not sent by the system

    • Register your receiver for action Intent.ACTION_PACKAGE_FIRST_LAUNCH at runtime and not in the manifest.

    Registering the broadcast receiver:

    registerReceiver(new LaunchReceiver(), new IntentFilter(Intent.ACTION_PACKAGE_FIRST_LAUNCH));
    

    Sample broadcast receiver:

    public class LaunchReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getData() != null) {
                Log.d(TAG, "Package name: " + intent.getDataString().replace("package:", ""));
            }
        }
    }
    

    For more information, read the actual code here: PackageManagerService.notifyFirstLaunch()