Programmatically check Play Store for app updates
Asked Answered
B

20

117

I have put my app on the Google Play Store. It has been installed by lots of my company's customers. I understand the mechanism of how the app is intended to upgrade.

The users should check the auto-update check box in the Playstore app for each app they want to auto-update. However some users have unchecked it or not checked it in the first place.

The app I have written is for the care industry and is used by carers to deliver homecare. Some of our customers my have 1200 carers. They would have to call all the carers into the office to update the phones individually. This is obviously unacceptable.

Is there a way to programmatically check if there is an updated version of my app on the Play Store?

Could I have code that runs every time the user starts the app that checks the Play Store? If there is an updated version then the user could be directed to the Playstore. This will mean it is not essential to have the auto-update checked.

Bream answered 8/8, 2014 at 10:25 Comment(4)
Doesn't the play store already push a notification to the user if there is an update available to an app?Sikang
Does your application connect to the cloud/internet in away to an API you have wrote - As you could simply have a 'version' variable that you could update manually - on opening the application, check the local version with the cloud version - if they differ, suggest an updateBuskined
I used to use jsoup to do this, but now use a regex to extract the Current Version field.Glabrate
As of May 26th, 2022, Google has changed their Play Store page and have hidden the latest "Version" behind a clickable button that displays a modal. Instead of just parsing/scraping the page, we had to use a headless browser to click that button, display the modal and then parse the modal for the Version. What a PITA. If someone knows a better method, please share!Oratorian
F
59

Update 17 October 2019

https://developer.android.com/guide/app-bundle/in-app-updates

Update 24 april 2019:

Android announced a feature which will probably fix this problem. Using the in-app Updates API: https://android-developers.googleblog.com/2018/11/unfolding-right-now-at-androiddevsummit.html

Original:

As far a I know, there is no official Google API which supports this.

You should consider to get a version number from an API.

Instead of connecting to external APIs or webpages (like Google Play Store). There is a risk that something may change in the API or the webpage, so you should consider to check if the version code of the current app is below the version number you get from your own API.

Just remember if you update your app, you need to change the version in your own API with the app version number.

I would recommend that you make a file in your own website or API, with the version number. (Eventually make a cronjob and make the version update automatic, and send a notification when something goes wrong)

You have to get this value from your Google Play Store page (is changed in the meantime, not working anymore):

<div class="content" itemprop="softwareVersion"> x.x.x  </div>

Check in your app if the version used on the mobile is below the version nummer showed on your own API.

Show indication that she/he needs to update with a notification, ideally.

Things you can do

Version number using your own API

Pros:

  • No need to load the whole code of the Google Play Store (saves on data/bandwidth)

Cons:

  • User can be offline, which makes checking useless since the API can't be accessed

Version number on webpage Google Play Store

Pros:

  • You don't need an API

Cons:

  • User can be offline, which makes checking useless since the API can't be accessed
    • Using this method may cost your users more bandwidth/mobile data
    • Play store webpage could change which makes your version 'ripper' not work anymore.
Filipe answered 8/8, 2014 at 10:34 Comment(5)
Version number on webpage of Google Play Store now has Current Version listed as Varies with device any idea how this can be resolved or if any other alternative is available ??Namaqualand
use #19244805Dumpcart
Indeed. Came to this question as we no longer can access the html source of our own google play page when doing a webrequest. we receive a FileNotFoundException.Traveled
Would try something like looking for a div which contains the text. Current version/Huidige versie Find the first number and dots digit in the next divs. <div class="hAyfc"> <div class="BgcNfc">Huidige versie</div> <div> <span class="htlgb">1.0</span> </div>Filipe
Classname wil probably be changed in every update on their website.Filipe
H
39

Include JSoup in your apps build.gradle file :

dependencies {
    compile 'org.jsoup:jsoup:1.8.3'
}

and get current version like :

currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

And execute following thread :

private class GetVersionCode extends AsyncTask<Void, String, String> {
    @Override
    protected String doInBackground(Void... voids) {

    String newVersion = null;
    try {
        newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=it")
                .timeout(30000)
                .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(".hAyfc .htlgb")
                .get(7)
                .ownText();
        return newVersion;
    } catch (Exception e) {
        return newVersion;
    }
    }

    @Override
    protected void onPostExecute(String onlineVersion) {
        super.onPostExecute(onlineVersion);
        Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);
        if (onlineVersion != null && !onlineVersion.isEmpty()) {
            if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
                //show dialog
            }
        }
    }

For more details visit : http://revisitingandroid.blogspot.in/2016/12/programmatically-check-play-store-for.html

Hattie answered 13/3, 2016 at 10:49 Comment(9)
in @Override protected void onPostExecute(String onlineVersion) { } if condition for check version should not in Float value . Because it may throw error like this Invalid java.lang.NumberFormatException: Invalid float: "1.0.6" . So use this . if (!currentVersion.equalsIgnoreCase(onlineVersion)) { ....}Counterpane
Any idea about how to do it without Jsoup ?Haight
Dear @HiteshSahu , you will have to hit the playstore URL "play.google.com/store/apps/details?id=com.whatsapp&hl=en". This Open Page URL. Right click on the page and click on the option "View Page Source". In the html of page you can see an attribute : "<div class="content" itemprop="softwareVersion"> 1.2 </div>". You have to parse the html and get this flag manually.Hattie
getPackageManager().getPackageInfo(getPackageName(), 0).versionName You could just use BuildConfig.VERSION_NAME :)Redevelop
online version always returns null for me. Please what is the way forwardGreenman
Google doesn't put itemprop="softwareVersion" in the HTML anymore. I'd suggest updating the selector in the sample code but there's nothing it could really be updated to.Alltime
Updated the answerHattie
It's clearly a generated classname which could be changed anytime. You should not do this.Filipe
the async task now deprecated any suggestions?Staley
S
30

Firebase Remote Config could be a possible and reliable solution for now, since google didn't expose any api to it.

Check Firebase Remote Config Docs

Steps 1.Create a firebase project and add google_play_service.json to your project

2.Create keys like "android_latest_version_code" and "android_latest_version_name" in firebase console->Remote Config

3.Android Code

    public void initializeFirebase() {
        if (FirebaseApp.getApps(mContext).isEmpty()) {
            FirebaseApp.initializeApp(mContext, FirebaseOptions.fromResource(mContext));
        }
        final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
        FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
                                                              .setDeveloperModeEnabled(BuildConfig.DEBUG)
                                                              .build();
        config.setConfigSettings(configSettings);
}

Get current version name and code

int playStoreVersionCode = FirebaseRemoteConfig.getInstance().getString(
                "android_latest_version_code");
PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0);
int currentAppVersionCode = pInfo.versionCode; 
if(playStoreVersionCode>currentAppVersionCode){
//Show update popup or whatever best for you
}

4. And keep firebase "android_latest_version_code" and "android_latest_version_name" upto date with your current production version name and code.

Firebase remote config works on both Android and IPhone.

Sensibility answered 18/8, 2017 at 6:44 Comment(2)
See firebasetutorials.com/… for creating parameters in Firebase.Hardihood
I think, this solution can lead to compile error: Caused by: com.android.tools.r8.utils.AbortException: Error: null, Cannot fit requested classes in a single dex file (# methods: 68703 > 65536). In this case you should add MultiDex to your application.Hardihood
S
16

You can get current Playstore Version using JSoup with some modification like below:

@Override
protected String doInBackground(Void... voids) {

    String newVersion = null;
    try {
        newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=it")
                .timeout(30000)
                .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(".hAyfc .htlgb")
                .get(7)
                .ownText();
        return newVersion;
    } catch (Exception e) {
        return newVersion;
    }
}

@Override
protected void onPostExecute(String onlineVersion) {
    super.onPostExecute(onlineVersion);

    Log.d("update", "playstore version " + onlineVersion);
}

answer of @Tarun is not working anymore.

Sadowski answered 30/3, 2018 at 11:58 Comment(5)
This is working buddy but can i rely on this forever or will it change in the near future ??Subito
It is not recommended to rely on this because it's not a official solution.Sadowski
@Sadowski I create a class GetVersionCode that extends AsyncTask and when I write your code inside that class getPackageName() shows error. I tried this, GetVersionCode.this but nothing works.Leannleanna
Using .select(".hAyfc .htlgb").get(7) isn't robust against changes. I saw another solution using index 5 instead. To select the right one, I use an extended query .select(".hAyfc .BgcNfc:containsOwn(Current Version) + .htlgb.htlgb").first ().text ()Lezley
This is going to change, it's better not to embed this inside your app.Witwatersrand
H
16

enter image description here

Google has introduced in-app updates API

The API currently supports two flows:

  • The “immediate” flow is a full-screen user experience that guides the user from download to update before they can use your app.
  • The “flexible flow” allows users to download the update while continuing to use your app.
Hendry answered 29/5, 2019 at 8:41 Comment(0)
R
8

There's AppUpdater library. How to include:

  1. Add the repository to your project build.gradle:
allprojects {
    repositories {
        jcenter()
        maven {
            url "https://jitpack.io"
        }
    }
}
  1. Add the library to your module build.gradle:
dependencies {
    compile 'com.github.javiersantos:AppUpdater:2.6.4'
}
  1. Add INTERNET and ACCESS_NETWORK_STATE permissions to your app's Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  1. Add this to your activity:
AppUpdater appUpdater = new AppUpdater(this); 
appUpdater.start();
Rainier answered 28/7, 2017 at 12:24 Comment(2)
Not working anyhow. Using following code, please tell me what I am doing wrong.Photogenic
Hi, I think there's a bug. Please check this discussion github.com/javiersantos/AppUpdater/issues/132Rainier
N
8

@Tarun answer was working perfectly.but now isnt ,due to the recent changes from Google on google play website.

Just change these from @Tarun answer..

class GetVersionCode extends AsyncTask<Void, String, String> {

    @Override

    protected String doInBackground(Void... voids) {

        String newVersion = null;

        try {
            Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName()  + "&hl=en")
                    .timeout(30000)
                    .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();
            if (document != null) {
                Elements element = document.getElementsContainingOwnText("Current Version");
                for (Element ele : element) {
                    if (ele.siblingElements() != null) {
                        Elements sibElemets = ele.siblingElements();
                        for (Element sibElemet : sibElemets) {
                            newVersion = sibElemet.text();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newVersion;

    }


    @Override

    protected void onPostExecute(String onlineVersion) {

        super.onPostExecute(onlineVersion);

        if (onlineVersion != null && !onlineVersion.isEmpty()) {

            if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
                //show anything
            }

        }

        Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);

    }
}

and don't forget to add JSoup library

dependencies {
compile 'org.jsoup:jsoup:1.8.3'}

and on Oncreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    String currentVersion;
    try {
        currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    new GetVersionCode().execute();

}

that's it.. Thanks to this link

Nymphet answered 9/5, 2018 at 11:2 Comment(0)
W
7

Coming From a Hybrid Application POV. This is a javascript example, I have a Update Available footer on my main menu. If an update is available (ie. my version number within the config file is less than the version retrieved, display the footer) This will then direct the user to the app/play store, where the user can then click the update button.

I also get the whats new data (ie Release Notes) and display these in a modal on login if its the first time on this version.

On device Ready, set your store URL

        if (device.platform == 'iOS')
           storeURL = 'https://itunes.apple.com/lookup?bundleId=BUNDLEID';
        else
           storeURL = 'https://play.google.com/store/apps/details?id=BUNDLEID';

The Update Available method can be ran as often as you like. Mine is ran every time the user navigates to the home screen.

function isUpdateAvailable() {
    if (device.platform == 'iOS') {
        $.ajax(storeURL, {
            type: "GET",
            cache: false,
            dataType: 'json'
        }).done(function (data) {
            isUpdateAvailable_iOS(data.results[0]);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            commsErrorHandler(jqXHR, textStatus, false);
        });
    } else {
        $.ajax(storeURL, {
            type: "GET",
            cache: false
        }).done(function (data) {
            isUpdateAvailable_Android(data);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            commsErrorHandler(jqXHR, textStatus, false);
        });
    }
}

iOS Callback: Apple have an API, so very easy to get

function isUpdateAvailable_iOS (data) {
    var storeVersion = data.version;
    var releaseNotes = data.releaseNotes;
    // Check store Version Against My App Version ('1.14.3' -> 1143)
    var _storeV = parseInt(storeVersion.replace(/\./g, ''));
    var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
    $('#ft-main-menu-btn').off();
    if (_storeV > _appV) {
        // Update Available
        $('#ft-main-menu-btn').text('Update Available');
        $('#ft-main-menu-btn').click(function () {
            openStore();
        });

    } else {
        $('#ft-main-menu-btn').html('&nbsp;');
        // Release Notes
        settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
    }
}

Android Callback: PlayStore you have to scrape, as you can see the version is relatively easy to grab and the whats new i take the html instead of the text as this way I can use their formatting (ie new lines etc)

function isUpdateAvailable_Android(data) {
    var html = $(data);
    var storeVersion = html.find('div[itemprop=softwareVersion]').text().trim();
    var releaseNotes = html.find('.whatsnew')[0].innerHTML;
    // Check store Version Against My App Version ('1.14.3' -> 1143)
    var _storeV = parseInt(storeVersion.replace(/\./g, ''));
    var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
    $('#ft-main-menu-btn').off();
    if (_storeV > _appV) {
        // Update Available
        $('#ft-main-menu-btn').text('Update Available');
        $('#ft-main-menu-btn').click(function () {
            openStore();
        });

    } else {
        $('#ft-main-menu-btn').html('&nbsp;');
        // Release Notes
        settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
    }
}

The open store logic is straight forward, but for completeness

function openStore() {
    var url = 'https://itunes.apple.com/us/app/appname/idUniqueID';
    if (device.platform != 'iOS')
       url = 'https://play.google.com/store/apps/details?id=appid'
   window.open(url, '_system')
}

Ensure Play Store and App Store have been Whitelisted:

  <access origin="https://itunes.apple.com"/>
  <access origin="https://play.google.com"/>
Waw answered 30/11, 2016 at 17:18 Comment(2)
I am getting error "Error parsing ajax response: SyntaxError: Unexpected token <". when ajax get is called. Can you shed some light on this, what went wrong?Cuckoopint
ios or android? is your url correct? takes you to correct page on browser?Waw
B
5

Inside OnCreate method write below code..

VersionChecker versionChecker = new VersionChecker();
    try {
        latestVersion = versionChecker.execute().get();
        Toast.makeText(getBaseContext(), latestVersion , Toast.LENGTH_SHORT).show();

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }

this gives you play store version of app..

then you have to check app version as below

PackageManager manager = getPackageManager();
    PackageInfo info = null;
    try {
        info = manager.getPackageInfo(getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    assert info != null;
    version = info.versionName;

after that you can compare it with store version and setup your own update screens

if(version.equals(latestVersion)){
        Toast.makeText(getBaseContext(), "No Update" , Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(getBaseContext(), "Update" , Toast.LENGTH_SHORT).show();

    }

And add VersionChecker.class as below

public class VersionChecker extends AsyncTask<String, String, String> {

    private String newVersion;

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

        try {
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + "package name" + "&hl=en")
                    .timeout(30000)
                    .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(".hAyfc .htlgb")
                    .get(7)
                    .ownText();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newVersion;
    }
}
Bipartite answered 21/8, 2018 at 5:19 Comment(0)
K
5

Firebase Remote Config is better.

  • Quickly and easily update our applications without the need to publish a new build to the app

Implementing Remote Config on Android

Adding the Remote Config dependancy

compile 'com.google.firebase:firebase-config:9.6.0'

Once done, we can then access the FirebaseRemoteConfig instance throughout our application where required:

FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();

Retrieving Remote Config values

boolean someBoolean = firebaseRemoteConfig.getBoolean("some_boolean");
byte[] someArray = firebaseRemoteConfig.getByteArray("some_array");
double someDouble = firebaseRemoteConfig.getDouble("some_double");
long someLong = firebaseRemoteConfig.getLong("some_long");
String appVersion = firebaseRemoteConfig.getString("appVersion");

Fetch Server-Side values

firebaseRemoteConfig.fetch(cacheExpiration)
            .addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        mFirebaseRemoteConfig.activateFetched();
                        // We got our config, let's do something with it!
                        if(appVersion < CurrentVersion){
                           //show update dialog
                        }
                    } else {
                        // Looks like there was a problem getting the config...
                    }
                }
            });

Now once uploaded the new version to playstore, we have to update the version number inside firebase. Now if it is new version the update dialog will display

Kodak answered 25/9, 2018 at 4:47 Comment(0)
C
4

Set up a server that exposes an HTTP url that reports the latest version, then use an AlarmManager to call that URL and see if the version on the device is the same as the latest version. If it isn't pop up a message or notification and send them to the market to upgrade.

There are some code examples: How to allow users to check for the latest app version from inside the app?

Caleb answered 8/8, 2014 at 10:33 Comment(0)
T
3

Apart from using JSoup, we can alternatively do pattern matching for getting the app version from playStore.

To match the latest pattern from google playstore ie <div class="BgcNfc">Current Version</div><span class="htlgb"><div><span class="htlgb">X.X.X</span></div> we first have to match the above node sequence and then from above sequence get the version value. Below is the code snippet for same:

    private String getAppVersion(String patternString, String inputString) {
        try{
            //Create a pattern
            Pattern pattern = Pattern.compile(patternString);
            if (null == pattern) {
                return null;
            }

            //Match the pattern string in provided string
            Matcher matcher = pattern.matcher(inputString);
            if (null != matcher && matcher.find()) {
                return matcher.group(1);
            }

        }catch (PatternSyntaxException ex) {

            ex.printStackTrace();
        }

        return null;
    }


    private String getPlayStoreAppVersion(String appUrlString) {
        final String currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>";
        final String appVersion_PatternSeq = "htlgb\">([^<]*)</s";
        String playStoreAppVersion = null;

        BufferedReader inReader = null;
        URLConnection uc = null;
        StringBuilder urlData = new StringBuilder();

        final URL url = new URL(appUrlString);
        uc = url.openConnection();
        if(uc == null) {
           return null;
        }
        uc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
        inReader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        if (null != inReader) {
            String str = "";
            while ((str = inReader.readLine()) != null) {
                           urlData.append(str);
            }
        }

        // Get the current version pattern sequence 
        String versionString = getAppVersion (currentVersion_PatternSeq, urlData.toString());
        if(null == versionString){ 
            return null;
        }else{
            // get version from "htlgb">X.X.X</span>
            playStoreAppVersion = getAppVersion (appVersion_PatternSeq, versionString);
        }

        return playStoreAppVersion;
    }

I got it solved through this, as this works for latest Google playstore changes also. Hope that helps.

Triple answered 23/5, 2018 at 3:51 Comment(0)
T
3
private void CheckUPdate() {
    VersionChecker versionChecker = new VersionChecker();
    try
    {   String appVersionName = BuildConfig.VERSION_NAME;
        String mLatestVersionName = versionChecker.execute().get();
        if(!appVersionName.equals(mLatestVersionName)){
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
            alertDialog.setTitle("Please update your app");
            alertDialog.setMessage("This app version is no longer supported. Please update your app from the Play Store.");
            alertDialog.setPositiveButton("UPDATE NOW", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    final String appPackageName = getPackageName();
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
                    } catch (android.content.ActivityNotFoundException anfe) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
                    }
                }
            });
            alertDialog.show();
        }

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}

@SuppressLint("StaticFieldLeak")
public class VersionChecker extends AsyncTask<String, String, String> {
    private String newVersion;
    @Override
    protected String doInBackground(String... params) {

        try {
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id="+getPackageName())
                    .timeout(30000)
                    .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(".hAyfc .htlgb")
                    .get(7)
                    .ownText();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newVersion;
    }
}
Transudation answered 13/10, 2018 at 12:18 Comment(1)
Please provide some information about how and what this code will workAalborg
G
3

I am not sure about JAVA programming though, but with latest changes you can

  1. Request https://play.google.com/store/apps/details?id=<package.name> url.
  2. Parse the data as text.
  3. Match regex /key: 'ds:4',\n[\ ]*hash: '[0-9]*',\n[\ ]*data:\ ([\S".,\[\]\ ]*),/ with the response.
  4. This has a group with it which will give group value as ["size", "version", "supported android version"]. e.g. ["16M", "1.0.0", "5.0 and up"].
  5. Parse the group as an array and you will get array[1] as latest version.

Implementation doesn't depend on any language.

Gauche answered 4/11, 2021 at 6:1 Comment(1)
Can you share full working code?Kally
A
2

There is no official GooglePlay API to do it.

But you can use this unofficial library to get app version data.

And, if the above doesn't work for you, you can always http connect to your app's page (e.g. https://play.google.com/store/apps/details?id=com.shots.android&hl=en) and parse the "Current Version" field.

Agram answered 8/8, 2014 at 10:30 Comment(1)
This lib is from 2011 and broken long agoIntine
T
2

You can try following code using Jsoup

String latestVersion = doc.getElementsContainingOwnText("Current Version").parents().first().getAllElements().last().text();
Tetanize answered 19/4, 2018 at 15:25 Comment(0)
B
2

Google introduced In-app updates feature, (https://developer.android.com/guide/app-bundle/in-app-updates) it works on Lollipop+ and gives you the ability to ask the user for an update with a nice dialog (FLEXIBLE) or with mandatory full-screen message (IMMEDIATE).

Here is how Flexible update will look like: enter image description here

and here is Immedtiate update flow: enter image description here

You can check my answer here https://mcmap.net/q/151736/-prompt-android-app-user-to-update-app-if-current-version-lt-gt-market-version to get the complete sample code of implementing both Flexible and Immediate update flows. Hope it helps!

Behindhand answered 28/6, 2019 at 18:11 Comment(0)
S
1

confirmed only that method work now:

newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + AcMainPage.this.getPackageName() + "&hl=it")
                        .timeout(30000)
                        .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(".hAyfc .htlgb")
                        .get(5)
                        .ownText();
Stellastellar answered 18/4, 2018 at 18:41 Comment(0)
M
1

enter image description hereGoogle introduced in-app update api. Using that we can ask user to update app inside the application. if user accept we can directly download latest app and install without redirect to playstore. for more details please refer the below link

link1link2

My answered 24/4, 2019 at 13:22 Comment(1)
I like the GIF you made :)Inborn
M
0

if your app is on Google Play Store then Just use this function its automatically checks the app update and shows a msg to the user for update

public void checkUpdate()
{
    if (isInternetOn())
    {
        AppUpdateManager appUpdateManager = AppUpdateManagerFactory.create(getApplicationContext());
        Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
        appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE))
            {
                try {
                    appUpdateManager.startUpdateFlowForResult(appUpdateInfo, AppUpdateType.FLEXIBLE, this, "Your Request Code");
                } catch (IntentSender.SendIntentException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

and additionally you can check internet Connectivity before checking the update with this function`

public boolean isInternetOn() 
    {
        
        ConnectivityManager connec = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) 
        {
            
            return true;

        } else if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) 
        {
            return false;
        }
        return false;
    }`
Moody answered 6/1, 2022 at 15:39 Comment(3)
What library does AppUpdateManager belong to?Hunnicutt
it belongs to google, bro check it developer.android.com/guide/playcore/in-app-updates/kotlin-javaButyrin
Two questions: 1. If the app is closed, will he get addOnSuccessListener callback when he'll launch the app? 2. Why do we need to check isInternetOn(), it should work anyway, right?Striated

© 2022 - 2024 — McMap. All rights reserved.