Search code examples
androidandroid-versionandroid-update-app

How to detect Android App has been upgraded from version x to y?


I have a problem with my android app for own educational reason.

Is there a ready solution to detect that the app has now been updated from version x to y? Because I want to migrate some data once only if the app was installed in a special version before.

Thanks.


Solution

  • Here is a simple way that can solve your problem. In your code you can easily get the app versionCode and versionName. In your home activity you check isAppUpdated(). if current APP VERSION_NAME is not matched with stored VERSION_NAME then app is updated.

    Here is sample code:

    Save VersionName in preferences:

    public static void saveVersionNameAndCode(Context context){
            try{
                PackageInfo packageInfo = context.getPackageManager()
                        .getPackageInfo(context.getPackageName(), 0);
                int versionCode = packageInfo.versionCode;
                String versionName=packageInfo.versionName;
    
                CommonTasks.showLog("Saving APP VersionCode and Version Name");
    
                // SAVE YOUR DATA
    
            }catch(Exception e){
            }
        }
    

    Check App is Upgraded:

    public static boolean isAppUpdated(Context context){
            boolean result=false;
            try{
                PackageInfo packageInfo = context.getPackageManager()
                        .getPackageInfo(context.getPackageName(), 0);
                int versionCode = packageInfo.versionCode;
                String versionName=packageInfo.versionName;
    
                String prevVersionName= GET STORED VERSION_NAME;
                if(prevVersionName!=null && !prevVersionName.equals("") &&
                        !prevVersionName.equals(versionName)){
                    showLog("App Updated");
                    result=true;
                }else{
                    showLog("App Not updated");
                }
    
            }catch(Exception e){
            }
            return result;
        }
    

    here, if isAppUpdated() return true means your app is updated.

    Note, After checking upgrade issue, you must have to update the sharedPreferences. :)