How to get app market version information from google play store?
Asked Answered
M

22

54

How can I get the application version information from google play store for prompting the user for force/recommended an update of the application when play store application is updated i.e. in case of the user is using old version application. I have already gone through andorid-market-api which is not the official way and also requires oauth login authentication from google. I have also gone through android query which provides in-app version check, but it is not working in my case. I found the following two alternatives:

  • Use server API which will store version info
  • Use google tags and access it in-app, which is not a preferred way to go.

Are there any other ways to do it easily?

Molybdate answered 16/12, 2015 at 10:29 Comment(10)
I prefer your first way...Dene
@CapDroid Is there any other way to do it? especially in case of standalone apps.Molybdate
I don't know :( mostly I am following your first way :)Dene
Taking the first the first approach, though it would be interesting to learn, if there're any another options. good question!Chinaman
Possible duplicate of Checking my app version programmatically in Android marketAccompany
I have already tried the market API which is not working now! The question you mentioned has answer which mentioned tonuse market API. So no duplicate questionMolybdate
Try this: github.com/googlesamples/android-play-publisher-api/tree/master/…Tutti
https://mcmap.net/q/187345/-programmatically-check-play-store-for-app-updatesMonique
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!Microelement
The version number is actually available within the new play store page without having to do a virtual button click eg: [[["2.0.102"]],[[[30,"11"]],[[[22,"5.1"]]]],[["May 15, 2022"]]] It is possible to find this string in a very fragile way currently by searching for: [null,null,[]],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[[["Meliorism
R
51

I recommend to not use a library just create a new class

1.

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

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("div.hAyfc:nth-child(4) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
                .first()
                .ownText();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return newVersion;
}
  1. In your activity:

         VersionChecker versionChecker = new VersionChecker();
         String latestVersion = versionChecker.execute().get();
    

THAT IS ALL

Recur answered 8/4, 2016 at 21:35 Comment(20)
what will be the output of this? I'm not getting this! Is it output version info? If yes, then in what format?Molybdate
you will get a string of the versionName, you can find this version name in the file "build.gradle".Recur
This is a hack. But it's a really nice hack that doesn't require much effort, especially considering that Google makes it hard to work with their apis. +1. :)Countersign
Nice hack, but not necessary anymore since this: github.com/googlesamples/android-play-publisher-api/tree/master/…Tutti
Thank you...a hack but beautiful.Morrill
@SandroWiggers which method from official API does check app version?Guenevere
Ya it can fail for a number of reasons. e.g., 1. Google changes the keys that you use in select("div[itemprop=softwareVersion]"). The best thing to do is to maintain an API on your own server that gives you the current market version of your app which you can then compare with the one installed on the users deviceOcieock
This just broken. If you're using regular expression instead you can use <div[^>]*?>Current Version</div><div><span[^>]*?>(.*?)</span></div>Cynde
True this way is broken. The expression you provided is also not working @CyndeTriplex
@Triplex They seem to be changing it atm. Let's see what ends up being "stable".Cynde
I got this working after fixing the pattern with "\s" between Current Version: <div[^>]*?>Current\sVersion</div><div><span[^>]*?>(.*?)</span></div>Outclass
.select("<div[^>]*?>Current\\sVersion</div><div><span[^>]*?>(.*?)</span></div>") produces this error Method threw 'org.jsoup.select.Selector$SelectorParseException' exception @OutclassTriplex
For android user add this dependency in gradle file, compile 'org.jsoup:jsoup:1.11.3'Kenaz
Seriously man.. I'm just trying trying n trying since morning finally this one worked... Thank you so much...Stocking
So, has anyone tried the android-play-publisher-api to get the current version number? I skimmed through the code but didn't find any hint that it could be used for that.Roxannroxanna
Is there no official way to do this. I mean you just read the html website. Not the prettiest way.Edi
This is also downloading a huge pile of HTML data (as of today it's 780 Kilobytes) over the user's mobile data connection. Not everybody is in California and has an unlimited data plan. This code is not just not robust, it's also a huge nuisance to users.Refuse
Nowadays the regex is <div[^>]*?>Current Version</div><span[^>]*?><div[^>]*?><span[^>]*?>(.*?)</span></div></span>Risner
As of today . Play Store UI is updated and version is moved to a popup. This logic doesnt work any more :(Prolongate
Hello, can anyone please give me latest way to find it, I have been finding this from so long but I am not able to get itStormi
C
23

Current solution

This is super hacky, but best I could come up quickly. Seemed to work with all apps I tried. PHP solution, but you can just pick the preg_match() regex part for any other language.

public function getAndroidVersion(string $storeUrl): string
{
    $html = file_get_contents($storeUrl);
    $matches = [];
    preg_match('/\[\[\[\"\d+\.\d+\.\d+/', $html, $matches);
    if (empty($matches) || count($matches) > 1) {
        throw new Exception('Could not fetch Android app version info!');
    }
    return substr(current($matches), 4);
}

Solution until May 2022 (NO LONGER WORKS)

Using PHP backend. This has been working for a year now. It seems Google does not change their DOM that often.

public function getAndroidVersion(string $storeUrl): string
{
    $dom = new DOMDocument();
    $dom->loadHTML(file_get_contents($storeUrl));
    libxml_use_internal_errors(false);
    $elements = $dom->getElementsByTagName('span');

    $depth = 0;
    foreach ($elements as $element) {
        foreach ($element->attributes as $attr) {
            if ($attr->nodeName === 'class' && $attr->nodeValue === 'htlgb') {
                $depth++;
                if ($depth === 7) {
                    return preg_replace('/[^0-9.]/', '', $element->nodeValue);
                    break 2;
                }
            }
        }
    }
}

Even older version (NO LONGER WORKS)

Here is jQuery version to get the version number if anyone else needs it.

    $.get("https://play.google.com/store/apps/details?id=" + packageName + "&hl=en", function(data){
        console.log($('<div/>').html(data).contents().find('div[itemprop="softwareVersion"]').text().trim());
    });
Clareclarence answered 30/9, 2016 at 11:17 Comment(6)
i need for ionic but when i am using it then getting some cors issue ,Epimenides
This is super brittle. How do I know? An app I've inherited does this and has started crashing hard today.Abney
I don't see softwareVersion in output of this command. It's probably changedPinery
@Pinery This has not been working for long time now. Their DOM has been stable thou. I have been parsing the DOM. Currently looking for class: htlgbClareclarence
thank you for the current solution, you saved me lot of time after Google updated the UI in May 2022Dremadremann
Regex for C# : var rx = new Regex(@"""\d+\.\d+\.\d", RegexOptions.Compiled);Blotter
F
16

I suspect that the main reason for requesting app's version is for prompting user for update. I am not in favour of scraping the response, because this is something that could break functionality in future versions.

If app's minimum version is 5.0, you can implement in-app update according to the documentation https://developer.android.com/guide/app-bundle/in-app-updates

If the reason of requesting apps version is different, you can still use the appUpdateManager in order to retrieve the version and do whatever you want (e.g. store it in preferences).

For example we can modify the snippet of the documentation to something like that:

// Creates instance of the manager.
val appUpdateManager = AppUpdateManagerFactory.create(context)

// Returns an intent object that you use to check for an update.
val appUpdateInfoTask = appUpdateManager.appUpdateInfo

// Checks that the platform will allow the specified type of update.
appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
    val version = appUpdateInfo.availableVersionCode()
    //do something with version. If there is not a newer version it returns an arbitary int
}
Frisbie answered 8/8, 2019 at 8:37 Comment(2)
Best solution, this is an official way to get app update informationSayyid
This one still only gives the versionCode, not the versionName where we have the semantic versioning (major,minor,patch) and based on that we can easily decide the soft/hard update.Majolica
B
8

Use this code its perfectly working fine.

public void forceUpdate(){
    PackageManager packageManager = this.getPackageManager();
    PackageInfo packageInfo = null;
    try {
        packageInfo =packageManager.getPackageInfo(getPackageName(),0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    String currentVersion = packageInfo.versionName;
    new ForceUpdateAsync(currentVersion,TodayWork.this).execute();
}

public class ForceUpdateAsync extends AsyncTask<String, String, JSONObject> {

    private String latestVersion;
    private String currentVersion;
    private Context context;
    public ForceUpdateAsync(String currentVersion, Context context){
        this.currentVersion = currentVersion;
        this.context = context;
    }

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

        try {
            latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + context.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()
                    .select("div.hAyfc:nth-child(3) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
                    .first()
                    .ownText();
            Log.e("latestversion","---"+latestVersion);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JSONObject();
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        if(latestVersion!=null){
            if(!currentVersion.equalsIgnoreCase(latestVersion)){
                // Toast.makeText(context,"update is available.",Toast.LENGTH_LONG).show();
                if(!(context instanceof SplashActivity)) {
                    if(!((Activity)context).isFinishing()){
                        showForceUpdateDialog();
                    }
                }
            }
        }
        super.onPostExecute(jsonObject);
    }

    public void showForceUpdateDialog(){

        context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
    }

}
Bontebok answered 25/5, 2018 at 9:20 Comment(0)
U
7

Firebase Remote Config can help best here,

Please refer this answer https://mcmap.net/q/187345/-programmatically-check-play-store-for-app-updates

Untinged answered 18/8, 2017 at 6:47 Comment(0)
U
5

Working in 2022

JS example (can be ported to any other language):

import { JSDOM } from 'jsdom'; 
import axios from 'axios';

const res = await axios('https://play.google.com/store/apps/details?id=com.yourapp');
const dom = new JSDOM(res.data);
const scripts = Array.from(dom.window.document.querySelectorAll('script'));
const script = scripts.find(s => s.textContent && s.textContent.includes('/store/apps/developer'));
const versionStringRegex = /"[0-9]+\.[0-9]+\.[0-9.]+"/g;
const matches = script.textContent.match(versionStringRegex);
const match = matches[0];
const version = match.replace(/"/g, '');

console.log(version); // '1.2.345'

Unfortunately, the play store recently changed their DOM layout such that the version number is not visible unless you open a modal.

However - buried as metadata in one of the script tags - the data that eventually gets rendered into that modal does indeed exist. It's not keyed in any way, but rather it's just buried in an array so this solution relies on some data in the same vicinity that is unlikely to change.

Undeniable answered 28/5, 2022 at 0:19 Comment(7)
I think your solution work with new Play Console update but I want android native code for same answer. Can you please provide me Android Native code so I will check.Criminality
@cooper-maruyama What is versionStringRegex?Syntax
@Larry Aasen Do you have Android Native code for this?Criminality
@Criminality No, I was planning to reproduce this in Dart for Flutter.Syntax
@Larry Aasen Okay then share dart code i will convert it in Android Native code.Criminality
@LarryAasen updated to include itUndeniable
Currently the textContent includes '/store/apps/dev' instead of '/store/apps/developer'.Alcus
T
4

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 this solved through this. This also solves the latest changes done by Google in PlayStore. Hope that helps.

Teacart answered 23/5, 2018 at 3:1 Comment(2)
I'll post the full code using AsynsTask with your permissionDoings
Not relaying on the word "Current Version" is more robust as the user may have different locacle preferenceChardin
B
3

Use server API which will store version info

Like you said.This is an easy way to detect an update. Pass your version info with every API calls. When playstore is updated change the version in server. Once the server version is higher than installed app version, you can return a status code/message in API response which can be handled and update message can be showed. You can also block users from using very old app like WhatsApp do if u use this method.

Or you can use push notification, which is easy to do...Also

Breughel answered 21/12, 2015 at 19:13 Comment(6)
I'm looking for the solution other than server API. Thanks for the reply!Molybdate
Try this google official api: github.com/googlesamples/android-play-publisher-api/tree/master/…Tutti
How to Use in Cakephp 2.0Sandell
Every API call seems like overkill to me.Essa
Don't add a new api call. Add version information in api. refer github.com/mindhaq/restapi-versioning-springBreughel
But if you use this method, the update needs to be reviewed by the google team and how do you know when to change the version in the API?Disgrace
I
3

Full source code for this solution: https://mcmap.net/q/335248/-how-to-get-app-market-version-information-from-google-play-store

import android.os.AsyncTask;
import android.support.annotation.Nullable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class GooglePlayAppVersion extends AsyncTask<String, Void, String> {

    private final String packageName;
    private final Listener listener;
    public interface Listener {
        void result(String version);
    }

    public GooglePlayAppVersion(String packageName, Listener listener) {
        this.packageName = packageName;
        this.listener = listener;
    }

    @Override
    protected String doInBackground(String... params) {
        return getPlayStoreAppVersion(String.format("https://play.google.com/store/apps/details?id=%s", packageName));
    }

    @Override
    protected void onPostExecute(String version) {
        listener.result(version);
    }

    @Nullable
    private static String getPlayStoreAppVersion(String appUrlString) {
        String
              currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>",
              appVersion_PatternSeq = "htlgb\">([^<]*)</s";
        try {
            URLConnection connection = new URL(appUrlString).openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder sourceCode = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) sourceCode.append(line);

                // Get the current version pattern sequence
                String versionString = getAppVersion(currentVersion_PatternSeq, sourceCode.toString());
                if (versionString == null) return null;

                // get version from "htlgb">X.X.X</span>
                return getAppVersion(appVersion_PatternSeq, versionString);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Nullable
    private static String getAppVersion(String patternString, String input) {
        try {
            Pattern pattern = Pattern.compile(patternString);
            if (pattern == null) return null;
            Matcher matcher = pattern.matcher(input);
            if (matcher.find()) return matcher.group(1);
        } catch (PatternSyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

}

Usage:

new GooglePlayAppVersion(getPackageName(), version -> 
    Log.d("TAG", String.format("App version: %s", version)
).execute();
Insidious answered 24/9, 2018 at 15:20 Comment(0)
N
3

C# solution at 2022 for my Xamarin app

var url = $"https://play.google.com/store/apps/details?id={_packageName}";
using (var request = new HttpRequestMessage(HttpMethod.Get, url))
{
   using (var handler = new HttpClientHandler())
   {
      using (var client = new HttpClient(handler))
      {
         using (var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead))
         {
            try
            {
               if (response.IsSuccessStatusCode)
               {
                  var content = response.Content == null ? null : await response.Content.ReadAsStringAsync();
                  var versionMatch = Regex.Match(content, @"\[\[""\d+.\d+.\d+""\]\]"); //look for pattern [["X.Y.Z"]]
                  if (versionMatch.Groups.Count == 1)
                  {
                     var versionMatchGroup = versionMatch.Groups.FirstOrDefault();
                     if (versionMatchGroup.Success)
                        return versionMatch.Value.Replace("[", "").Replace("]", "").Replace("\"", "");
                  }
               }
            }
            catch
            { }
         }
      }
   }
}
return null;
Neoclassicism answered 26/10, 2022 at 19:33 Comment(0)
B
2

Kotlin 2022

Google updated the layout that was unchanged for years and old parsers don't work anymore. Here is my parser from 2022

import io.ktor.client.*
import io.ktor.client.features.*
import io.ktor.client.request.*
import io.ktor.http.*

class AppVersionParser {

 private val client = HttpClient {
    install(HttpTimeout.Feature)
 }

 suspend fun versionForIdentifier(bundleID: String, privacyUrl: String): String? {
    val userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_3_1) AppleWebKit/605.1.15 (KHTML, like Gecko) " +
        "Version/15.3 Safari/605.1.15"
    val referrer = "https://www.google.com"

    val url = "https://play.google.com/store/apps/details?id=$bundleID&hl=en"

    return try {
        val response: String = client.get(url) {
            headers {
                this.append(HttpHeaders.UserAgent, userAgent)
                this.append(HttpHeaders.Referrer, referrer)
            }

            timeout {
                this.requestTimeoutMillis = 10000
            }
        }

        parseDocument(response, privacyUrl)
    } catch (e: Exception) {
        return null
    }
  }

  private fun parseDocument(html: String, privacyUrl: String): String {
    val policyMarker = "\"${privacyUrl}\""
    val policyUrlIndex = html.lastIndexOf(policyMarker)
    val versionStart = html.indexOf("\"", startIndex = policyUrlIndex + policyMarker.length + 1) + 1 // "
    val versionEnd = html.indexOf("\"", startIndex = versionStart + 1)
    return html.substring(startIndex = versionStart, endIndex = versionEnd)
  }
}
Beutler answered 27/5, 2022 at 20:35 Comment(9)
does it work on the new play store designChapnick
does it work on the new play store designChapnick
@Chapnick Yes, it is made exactly for the new play store design. Vote up if it works for you to show others.Beutler
Can you share android native code ?Criminality
@Criminality this is Kotlin alreadyBeutler
I don't understand what you are doing there but it works.. +1 edit: now I got itHoo
What does the privacyUrl field consist of? I'm translating the parse function for my c# xamarin app :)Neoclassicism
@Neoclassicism privacy URL of the appBeutler
does it still work in 2023?Stormi
I
2

With the new google play page, it's possible to extract the data in the AF_initDataCallback calls, parse it to get the version string. Here is the code in ts/js code to parse the data:

import json5 from "json5";

const packageId = "com.and.games505.TerrariaPaid";
const gplayResponse = await fetch(`https://play.google.com/store/apps/details?id=${packageId}`);
const siteText = await gplayResponse.text();
const matches = siteText.matchAll(/<script nonce=\"\S+\">AF_initDataCallback\((.*?)\);/g);

for (const match of matches) {
    const data = json5.parse(match[1]); // json5 parse or js eval should work here
    try {
        return data["data"][1][2][140][0][0][0];
    } catch {}
}

I have a cloudflare worker hosted here that returns the version code: https://gplay-ver.atlasacademy.workers.dev/?id=com.and.games505.TerrariaPaid

Source code

Intercom answered 12/8, 2022 at 9:13 Comment(1)
This works still splendidly, although I didn't want to bother with nested data blocks. I just scan for the actual version, which consists of major.minor.micro and is easy to find. For completeness, here's a Ruby excerpt that I used in an AsciiDoc ext: data.scan(/<script nonce=\"\S+\">AF_initDataCallback\((.*?)\);/) do |match| begin matches = match.first.scan(/(\d+\.\d+\.\d+)/) retVal = matches.first.first unless matches.nil? or matches.empty? rescue => err p err end unless match.nil? end unless data.nil?Springe
M
1

User Version Api in Server Side:

This is the best way still now to get the market version. When you will upload new apk, update the version in api. So you will get the latest version in your app. - This is best because there is no google api to get the app version.

Using Jsoup Library:

This is basically web scraping. This is not a convenient way because if google changes their code This process will not work. Though the possiblity is less. Anyway, To get the version with Jsop library.

  1. add this library in your build.gradle

    implementation 'org.jsoup:jsoup:1.11.1'

  2. Creat a class for version check:

import android.os.AsyncTask import org.jsoup.Jsoup import java.io.IOException

class PlayStoreVersionChecker(private val packageName: String) : AsyncTask() {

private var playStoreVersion: String = ""

override fun doInBackground(vararg params: String?): String {
    try {
        playStoreVersion =
                Jsoup.connect("https://play.google.com/store/apps/details?id=$packageName&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("div.hAyfc:nth-child(4) > span:nth-child(2) > div:nth-child(1) > span:nth-child(1)")
                    .first()
                    .ownText()
    } catch (e: IOException) {
    }
    return playStoreVersion
} }
  1. Now use the class as follows:

    val playStoreVersion = PlayStoreVersionChecker("com.example").execute().get()

Migration answered 12/5, 2020 at 9:32 Comment(0)
C
1

For PHP It helps for the php developers to get the version code of a particular play store app serverside

$package='com.whatsapp';
$html = file_get_contents('https://play.google.com/store/apps/details?id='.$package.'&hl=en');
preg_match_all('/<span class="htlgb"><div class="IQ1z0d"><span class="htlgb">(.*?)<\/span><\/div><\/span>/s', $html, $output);
print_r($output[1][3]);
Chromolithograph answered 2/6, 2020 at 16:18 Comment(0)
G
0

I will recommend to use ex. push notification to notify your app that there is a new update, OR use your own server to enable your app read version from there.

Yes its additional work each time you update your app, but in this case your are not depended on some "unofficial" or third party things that may run out of service.

Just in case you missed something - previous discussion of your topic query the google play store for the version of an app?

Germangermana answered 19/12, 2015 at 3:48 Comment(3)
I have tried android-market-api, which is not working now. I have also tried android-query and it is no more working.Molybdate
Yes, android-market-api seems doesn't work anymore for me too.Aspidistra
You can use this: github.com/googlesamples/android-play-publisher-api/tree/master/…Tutti
D
0

You can call the following WebService: http://carreto.pt/tools/android-store-version/?package=[YOUR_APP_PACKAGE_NAME]

Example Using Volley:

String packageName = "com.google.android.apps.plus";
String url = "http://carreto.pt/tools/android-store-version/?package=";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
    (Request.Method.GET, url+packageName, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        /*
                                here you have access to:

                                package_name, - the app package name
                                status - success (true) of the request or not (false)
                                author - the app author
                                app_name - the app name on the store
                                locale - the locale defined by default for the app
                                publish_date - the date when the update was published
                                version - the version on the store
                                last_version_description - the update text description
                             */
                        try{
                            if(response != null && response.has("status") && response.getBoolean("status") && response.has("version")){
                                Toast.makeText(getApplicationContext(), response.getString("version").toString(), Toast.LENGTH_LONG).show();
                            }
                            else{
                                //TODO handling error
                            }
                        }
                        catch (Exception e){
                            //TODO handling error
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //TODO handling error
                    }
        });
Dipole answered 1/9, 2016 at 16:26 Comment(2)
Should be easier: github.com/googlesamples/android-play-publisher-api/tree/master/…Tutti
How to Use in Cakephp 2.0Sandell
P
0

the easiest way is using firebase package from google and using remote notifications or realtime config with the new version and sent id to the users below up version number see more https://firebase.google.com/

Pedicab answered 17/10, 2017 at 23:6 Comment(0)
D
0

the benefits here thay you'll be able to check version number instead of name, that should be more convinient :) At the other hand - you should take care of updating version in api/firebase each time after release.

  • take version from google play web page. I have implemented this way, and it works more that 1 year, but during this time i have to change 'matcher' 3-4 times, because content on the web page were changed. Also it some head ache to check it from time to time, because you can't know where it can be changed. but if you still want to use this way, here is my kotlin code based on okHttp:

    private fun getVersion(onChecked: OnChecked, packageName: String) {
    
    Thread {
        try {
            val httpGet = HttpGet("https://play.google.com/store/apps/details?id="
                    + packageName + "&hl=it")
    
            val response: HttpResponse
            val httpParameters = BasicHttpParams()
            HttpConnectionParams.setConnectionTimeout(httpParameters, 10000)
            HttpConnectionParams.setSoTimeout(httpParameters, 10000)
            val httpclient = DefaultHttpClient(httpParameters)
            response = httpclient.execute(httpGet)
    
            val entity = response.entity
            val `is`: InputStream
            `is` = entity.content
            val reader: BufferedReader
            reader = BufferedReader(InputStreamReader(`is`, "iso-8859-1"), 8)
            val sb = StringBuilder()
            var line: String? = null
            while ({ line = reader.readLine(); line }() != null) {
                sb.append(line).append("\n")
            }
    
            val resString = sb.toString()
            var index = resString.indexOf(MATCHER)
            index += MATCHER.length
            val ver = resString.substring(index, index + 6) //6 is version length
            `is`.close()
            onChecked.versionUpdated(ver)
            return@Thread
        } catch (ignore: Error) {
        } catch (ignore: Exception) {
        }
    
        onChecked.versionUpdated(null)
    }.start()
    }
    
Deoxyribose answered 17/4, 2019 at 6:21 Comment(0)
C
0

My workaround is to parse the Google Play website and extract the version number. If you're facing CORS issue or want to save bandwidth on the user's device, consider to run it from your web server.

let ss = [html];

for (let p of ['div', 'span', '>', '<']) {
  let acc = [];
  ss.forEach(s => s.split(p).forEach(s => acc.push(s)));
  ss = acc;
}

ss = ss
  .map(s => s.trim())
  .filter(s => {
    return parseFloat(s) == +s;
  });

console.log(ss); // print something like [ '1.10' ]

You can get the html text by fetching https://play.google.com/store/apps/details?id=your.package.name. For comparability, you may use https://www.npmjs.com/package/cross-fetch which works on both browser and node.js.

Others have mentioned parsing the html from Google Play website with certain css class or pattern like "Current Version" but these methods may not be as robust. Because Google could change the class name any time. It may as well return text in different language according to the users' locale preference, so you may not get the word "Current Version".

Chardin answered 2/3, 2020 at 2:6 Comment(0)
V
0

Dart example. August 2023

import 'dart:core';
import 'package:dio/dio.dart';

Future<void> main() async {
  print(await getAndroidVersionFromGooglePlay('com.intervale.tips')); // 1.1.1
  print(await getAndroidVersionFromGooglePlay('game.rpg.action.cyber')); // 2.0.7-rc609
}

Future<String?> getAndroidVersionFromGooglePlay(String package) async {
  final Dio dio = Dio();

  // Get html containing code with application version. For example:
  // ...
  // ,[[["2.0.7-rc609"]]
  // ...
  final response = await dio.get('https://play.google.com/store/apps/details?id=$package');

  // Look for all ,[[[ pattern and split all matches into an array
  List<String> splitted = response.data.split(',[[["');

  // In each element, remove everything after "]] pattern
  List<String> removedLast = splitted.map((String e) {
    return e.split('"]],').first;
  }).toList();

  // We are looking for a version in the array that satisfies the regular expression:
  // starts with one or more digits (\d), followed by a period (.), followed by one or more digits.
  List<String> filteredByVersion = removedLast
      .map((String e) {
        RegExp regex = RegExp(r'^\d+\.\d+');
        if (regex.hasMatch(e)) {
          return e;
        }
      })
      .whereType<String>()
      .toList();

  if (filteredByVersion.length == 1) {
    return filteredByVersion.first;
  }

  return null;
}
Vaclav answered 17/8, 2023 at 11:41 Comment(0)
B
0

One fairly simple solution would be to put the version info into a publicly available file and just let your app download it. You just have to remember to update the file whenever you update your app. You could put it into a publicly available AWS S3 file, for instance. If you have your own server, you could put it there. Basically, make your own API that you know will never break.

Balling answered 2/10, 2023 at 1:51 Comment(0)
B
-1

According to Cooper Maruyama's answer I implemented a solution in python:

import urllib3
from bs4 import BeautifulSoup

def get_current_android_version_from_playstore(app_id: str):
    http = urllib3.PoolManager()
    url = 'https://play.google.com/store/apps/details?id=' + app_id + '&hl=de'

    r = http.request('GET', url)

    html_string = r.data.decode('utf-8')

    soup = BeautifulSoup(html_string, 'html.parser')
    scripts = soup.find_all('script')
    script_contents = list(map(lambda s: s.text, scripts))
    version_script_contents = list(filter(lambda s: '/store/apps/developer' in s, script_contents))

    if len(version_script_contents) != 1:
        raise Exception('Could not identify version script')

    # May update regex currently it supports only two digits after the last point
    results = re.findall(r"\"\d+\.\d+\.\d\d?\"", version_script_contents[0])
    if len(results) != 1:
        raise Exception('Could not find matching version regex')

    version = results[0].replace('"', '')

    return version
Briquet answered 31/5, 2022 at 6:7 Comment(4)
Is it working with Google New Design?Criminality
Yes it’s written for the new design.Briquet
Marco Weber I want android native code. I check this code in online tool it gives me error in regex. File <string>, line 18 results = re.findall(r"\"\d+\.\d+\.\d\d?\"", version_script_contents[0]) ^ SyntaxError: EOL while scanning string literalCriminality
yes I am also facing error, can you give me working codeStormi

© 2022 - 2024 — McMap. All rights reserved.