I want to add a "Check for update" button in apps so that when someone clicks it, it will display a toast message / progress dialog for checking the app's version.
If new version is found the apps will auto download it to the phone and let user to manually install the updated apps.
Or any others method will do as long as it can check for latest version and notify the user to update.
Update: Now you can do this inside your app using https://developer.android.com/guide/playcore/in-app-updates
This question is related to
java
android
http
versioning
If it is an application on the Market, then on app start-up, fire an Intent to open up the Market app hopefully which will cause it to check for updates.
Otherwise implementing and update checker is fairly easy. Here is my code (roughly) for it:
String response = SendNetworkUpdateAppRequest(); // Your code to do the network request
// should send the current version
// to server
if(response.equals("YES")) // Start Intent to download the app user has to manually install it by clicking on the notification
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("URL TO LATEST APK")));
Of course you should rewrite this to do the request on a background thread but you get the idea.
If you like something a little but more complex but allows your app to automatically apply the update see here.
add compile 'org.jsoup:jsoup:1.10.2'
to dependencies in APP LEVEL build.gradle
&
Just add below code and you are good to go.
private class GetVersionCode extends AsyncTask<Void, String, String> {
@Override
protected String doInBackground(Void... voids) {
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + SplashActivity.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("div[itemprop=softwareVersion]")
.first()
.ownText();
return newVersion;
} catch (Exception e) {
return newVersion;
}
}
@Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
if (!currentVersion.equalsIgnoreCase(onlineVersion)) {
//show dialog
new AlertDialog.Builder(context)
.setTitle("Updated app available!")
.setMessage("Want to update app?")
.setPositiveButton("Update", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
Toast.makeText(getApplicationContext(), "App is in BETA version cannot update", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
})
.setNegativeButton("Later", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
dialog.dismiss();
new MyAsyncTask().execute();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
I know the OP was very old, at that time in-app-update was not available. But from API 21, you can use in-app-update checking. You may need to keep your eyes on some points which are nicely written up here:
You can use this Android Library: https://github.com/danielemaddaluno/Android-Update-Checker. It aims to provide a reusable instrument to check asynchronously if exists any newer released update of your app on the Store. It is based on the use of Jsoup (http://jsoup.org/) to test if a new update really exists parsing the app page on the Google Play Store:
private boolean web_update(){
try {
String curVersion = applicationContext.getPackageManager().getPackageInfo(package_name, 0).versionName;
String newVersion = curVersion;
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[itemprop=softwareVersion]")
.first()
.ownText();
return (value(curVersion) < value(newVersion)) ? true : false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
And as "value" function the following (works if values are beetween 0-99):
private long value(String string) {
string = string.trim();
if( string.contains( "." )){
final int index = string.lastIndexOf( "." );
return value( string.substring( 0, index ))* 100 + value( string.substring( index + 1 ));
}
else {
return Long.valueOf( string );
}
}
If you want only to verify a mismatch beetween versions, you can change:
value(curVersion) < value(newVersion)
with value(curVersion) != value(newVersion)
To save time writing for check new version update for android app, I written it as library and open source at https://github.com/winsontan520/Android-WVersionManager
Here's how to find the current and latest available versions:
try {
String curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
String newVersion = curVersion;
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + 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(4) .IQ1z0d .htlgb")
.first()
.ownText();
Log.d("Curr Version" , curVersion);
Log.d("New Version" , newVersion);
} catch (Exception e) {
e.printStackTrace();
return false;
}
There is no API for this, and you can't auto install it, you can just redirect them to it's Market page so they can upgrade. You can have your latest version in a file on a Web server, and have the app check it. Here's one implementation of this:
http://code.google.com/p/openintents/source/browse/#svn%2Ftrunk%2FUpdateCheckerApp
Navigate to your play page:
https://play.google.com/store/apps/details?id=com.yourpackage
Using a standard HTTP GET. Now the following jQuery finds important info for you:
$("[itemprop='softwareVersion']").text()
$(".recent-change").each(function() { all += $(this).text() + "\n"; })
Now that you can extract these information manually, simply make a method in your app that executes this for you.
public static String[] getAppVersionInfo(String playUrl) {
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
props.setAllowHtmlInsideAttributes(true);
props.setAllowMultiWordAttributes(true);
props.setRecognizeUnicodeChars(true);
props.setOmitComments(true);
try {
URL url = new URL(playUrl);
URLConnection conn = url.openConnection();
TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
Object[] new_nodes = node.evaluateXPath("//*[@class='recent-change']");
Object[] version_nodes = node.evaluateXPath("//*[@itemprop='softwareVersion']");
String version = "", whatsNew = "";
for (Object new_node : new_nodes) {
TagNode info_node = (TagNode) new_node;
whatsNew += info_node.getAllChildren().get(0).toString().trim()
+ "\n";
}
if (version_nodes.length > 0) {
TagNode ver = (TagNode) version_nodes[0];
version = ver.getAllChildren().get(0).toString().trim();
}
return new String[]{version, whatsNew};
} catch (IOException | XPatherException e) {
e.printStackTrace();
return null;
}
}
Uses HtmlCleaner
I did using in-app updates. This will only with devices running Android 5.0 (API level 21) or higher,
You should first check the app version on the market and compare it with the version of the app on the device. If they are different, it may be an update available. In this post I wrote down the code for getting the current version of market and current version on the device and compare them together. I also showed how to show the update dialog and redirect the user to the update page. Please visit this link: https://stackoverflow.com/a/33925032/5475941
We can check Update by Add these Code:
First we need to add dependencies :
implementation 'org.jsoup:jsoup:1.10.2'
Second we need to create Java File :
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;
import org.jsoup.Jsoup;
public class CurrentVersion{
private Activity activity;
public CurrentVersion(Activity activity) {
this.activity = activity;
}
//current version of app installed in the device
private String getCurrentVersion(){
PackageManager pm = activity.getPackageManager();
PackageInfo pInfo = null;
try {
pInfo = pm.getPackageInfo(activity.getPackageName(),0);
} catch (PackageManager.NameNotFoundException e1) {
e1.printStackTrace();
}
return pInfo.versionName;
}
private class GetLatestVersion extends AsyncTask<String, String, String> {
private String latestVersion;
private ProgressDialog progressDialog;
private boolean manualCheck;
GetLatestVersion(boolean manualCheck) {
this.manualCheck = manualCheck;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (manualCheck)
{
if (progressDialog!=null)
{
if (progressDialog.isShowing())
{
progressDialog.dismiss();
}
}
}
String currentVersion = getCurrentVersion();
//If the versions are not the same
if(!currentVersion.equals(latestVersion)&&latestVersion!=null){
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("An Update is Available");
builder.setMessage("Its better to update now");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Click button action
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+activity.getPackageName())));
dialog.dismiss();
}
});
builder.setCancelable(false);
builder.show();
}
else {
if (manualCheck) {
Toast.makeText(activity, "No Update Available", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected String doInBackground(String... params) {
try {
//It retrieves the latest version by scraping the content of current version from play store at runtime
latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + activity.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 latestVersion;
} catch (Exception e) {
return latestVersion;
}
}
}
public void checkForUpdate(boolean manualCheck)
{
new GetLatestVersion(manualCheck).execute();
}
}
_x000D_
Third We need to add this class in your main class where you want to show the update:
AppUpdateChecker appUpdateChecker=new AppUpdateChecker(this);
appUpdateChecker.checkForUpdate(false);
I Hope it will Help you
Source: Stackoverflow.com