Android - Detect Application Update via Play Store

     Android application developers would in some cases want a logic to be executed every time the application is updated via Play store or even when a new version is side loaded. In some cases, the logic needs to be executed only on upgrades and not when the user downgrades the application for different reasons.

     Unfortunately, Android SDK doesn't offer an API to detect application updates. However, Android guarantees that the application specific user data wouldn't be erased. This is what lets user login work even after the application is upgraded. Few data is stored in Shared Preferences and this too wouldn't be deleted upon an update.

   Developers can just keep track of the application version in the Shared Preference and query the same on application start up to check if the current version is same as the last known book kept version. If not, it would be a new version. This can be used to even detect an upgrade or downgrade.

     SharedPreferences preferences = getSharedPreferences( PREFS_NAME, MODE_PRIVATE );
      previousVersionCode = editor.getInt("versionCode", -1);

      PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
      currentVersionCode = pInfo.versionCode;

      if ( previousVersionCode == -1 || currentVersionCode != previousVersionCode ) {
          // Either first launch after installation or Factory reset and new install or an update

          // Execute logic for an application update

          // Update the current version in Shared Preferences
          Editor editor = getSharedPreferences( PREFS_NAME, MODE_PRIVATE ).edit();
          editor.putInt( "versionCode", currentVersionCode );
          editor.commit();
      }

Update:

    It was pointed out that Android SDK does have a broadcast intent API (ACTION_MY_PACKAGE_REPLACED) for application updates. Handling this intent would still need some kind of persistent storage like SharedPreference as the device could be rebooted after an application update without a user launch into the application via Launcher. In any case, this would eliminates the logic around version codes but is supported only from API level 12.

No comments: