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