android check update version and show an update app message

First check App live version and then check current version. if not same update message will be thrown.

This code should be pasted on onCreate in Activity

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

} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}VersionChecker versionChecker = new VersionChecker();
try {
     latestVersion = versionChecker.execute().get();
    Toast.makeText(getBaseContext(), latestVersion , Toast.LENGTH_SHORT).show();

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


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

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

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

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

Create a update check class


import android.os.AsyncTask;

import org.jsoup.Jsoup;

import java.io.IOException;

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;
    }
}

Done 🙂

Alternatively you can use this library also

https://github.com/javiersantos/AppUpdater

Leave a Reply

Your email address will not be published. Required fields are marked *