Android In-app version check
Asked Answered
S

5

12

I want to check application version on google play when my app open. If App has higher version than the installed app, I want to notify user to update the app. I found that "android-query" jar from here, in this I can't check version dynamically on this, I suppose to set Major, Minor or Revision. Anyone please help me how can I do?

Thanks in advance

Stocky answered 5/8, 2013 at 4:58 Comment(4)
Hi Jonathon Reinhart, Sorry, I really don't understand. Can you please explain me?Stocky
This is done all the time by apps even google's own apps. Sometimes a backend service is updated in a way that is no longer compatible with old versions of apps in the wild. Thus, it may be required to do this in your app if you don't want to support 3 year old versions because some people never update anything.Floater
Found a solution here #7298606Elea
I wonder if I answered your question correctly?Geosphere
G
13

Basically, you should check the latest version of your app in the market and the version of the app on the device and decide if there is any update available. For doing this please try this:

You should use this for getting the current version (version of the app on the device):

private String getCurrentVersion(){
PackageManager pm = this.getPackageManager();
PackageInfo pInfo = null;

        try {
            pInfo =  pm.getPackageInfo(this.getPackageName(),0);

        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }
        String currentVersion = pInfo.versionName;

        return currentVersion;
    }

And use this for getting the latest version in the Google play (taken from https://mcmap.net/q/149595/-force-update-of-an-android-app-when-a-new-version-is-available):

private class GetLatestVersion extends AsyncTask<String, String, String> {
String latestVersion;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            //It retrieves the latest version by scraping the content of current version from play store at runtime
            String urlOfAppFromPlayStore = "https://play.google.com/store/apps/details?id= your app package address";
            Document  doc = Jsoup.connect(urlOfAppFromPlayStore).get();
            latestVersion = doc.getElementsByAttributeValue("itemprop","softwareVersion").first().text();

        }catch (Exception e){
            e.printStackTrace();

        }

        return latestVersion;
    }
}

Then, when your app starts, check them against each others like this:

String latestVersion = "";
        String currentVersion = getCurrentVersion();
        Log.d(LOG_TAG, "Current version = " + currentVersion);
        try {
            latestVersion = new GetLatestVersion().execute().get();
            Log.d(LOG_TAG, "Latest version = " + latestVersion);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //If the versions are not the same
        if(!currentVersion.equals(latestVersion)){
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("An Update is Available");
            builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //Click button action
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=your app package address")));
                    dialog.dismiss();
                }
            });

            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //Cancel button action
                }
            });

            builder.setCancelable(false);
            builder.show();
        }

And show the user update dialog. But make sure you already imported jsoup library.

Extra: For importing jsoup library, follow these steps:

1- go to File menu
2- project structure
3- left side click on app
4- Choose dependencies tab
5- Click on +
6- Click on library dependency
7- Search "jsoup"
8- choose org.jsoup:jsoup and click ok

Geosphere answered 25/11, 2015 at 19:36 Comment(5)
is there any way of without using jsoup lib\Hypogenous
Yes, there is, but this approach is modern and straight forward. for adding the jsoup you don't even need to find the jar file. You just open the Android studio go to File menu and follow my 8 steps then you can add jsoup by only searching the name jsoup. It is 1, 2, 3 approach :) Please let me know if you need more explanation.Geosphere
In future, ddo not copy content from elsewhere without clear attribution. It is seen as plagiarism. See stackoverflow.com/help/referencingReflectance
for now, same worked with me by adding small modification in above AsyncTask doInBackground function:Infelicity
what happens if the play store html page is changedLeicestershire
T
5

If you don't want to use a library like Jsoup, you can use something like this to get the current version number from Google Play:

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;

public class StackAppVersion {

    public static void main(String[] args) {
        try {
            System.out.println(currentVersion());
        } catch (IOException ex) {
            System.out.println("Failed to read Google Play page!");
        }
    }

    private static String currentVersion() throws IOException {
        StringBuilder sb = new StringBuilder();

        try (Reader reader = new InputStreamReader(
                new URL("https://play.google.com/store/apps/details?id=com.stackexchange.marvin&hl=en")
                        .openConnection()
                        .getInputStream()
                , "UTF-8"
        )) {
            while (true) {
                int ch = reader.read();
                if (ch < 0) {
                    break;
                }
                sb.append((char) ch);
            }
        } catch (MalformedURLException ex) {
            // Can swallow this exception if your static URL tests OK.
        }

        String parts[] = sb.toString().split("softwareVersion");

        return parts[1].substring(
                parts[1].indexOf('>') + 1, parts[1].indexOf('<')
        ).trim();
    }
}

If you keep the "&hl=en" in the URL, the character encoding UTF-8 should be OK.

Tunesmith answered 15/5, 2016 at 1:32 Comment(0)
I
3

Adding a slight modification in @Mohammad answer, for current play page, below worked for me.

 @Override
    protected String doInBackground(String... params) {

        try {
            Document doc = Jsoup.connect("https://play.google.com/store/apps/details?id=YOUR_PACKAGE_NAME").get();
            Element element = doc.getElementsByClass("BgcNfc").get(3);
            latestVersion = element.parent().children().get(1).children().text();
        } catch (Exception e) {
            latestVersion = currentVersion;
        }

        return latestVersion;
    }

***Its not a generic answer as it may change as play page make changes*

Infelicity answered 30/5, 2018 at 7:52 Comment(0)
S
2

Accepted answer is not working any longer. Recently I had to change the code.

Try the following:

Jsoup.connect("https://play.google.com/store/apps/details?id=APPPACKAGE&hl=en")
                .timeout(10000)
                .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .referrer("http://www.google.com")
                .get()
                .select("div:contains(Current Version)").last().parent()
                .select("span").last()
                .ownText();
Sheepdip answered 10/5, 2018 at 16:59 Comment(1)
Works perfectly and seems more future proof than other solutions. Make sure you put &hl=en at the end of the google play URL or it might fetch in another language and it won't work.Prescience
C
0

After A lot of searching online i managed to get to a working solution in that matter! so for everyone else out there looking for the right answer

protected String doInBackground(Void... voids) {

        StringBuilder sb = new StringBuilder();

        try (Reader reader = new InputStreamReader(
                new URL("https://play.google.com/store/apps/details?id="+BuildConfig.APPLICATION_ID+"&hl=en")
                        .openConnection()
                        .getInputStream()
                , "UTF-8"
        )) {
            while (true) {
                int ch = reader.read();
                if (ch < 0) {
                    break;
                }
                sb.append((char) ch);
            }
        } catch (MalformedURLException ex) {
            Log.d("ERROR", ex.getMessage());
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.d("ERROR", e.getMessage());
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("ERROR", e.getMessage());
            return null;
        }

        String parts[] = sb.toString().split("Current Version");
        String res = parts[1].substring(
                parts[1].indexOf("htlgb") + 7, parts[1].indexOf("htlgb") + 11
        ).trim().toString();
        return res;

    }
Cutright answered 3/4, 2018 at 13:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.