Reputation: 36205
I have an android app in the market and I've noticed that it can take quite a while for the app to be updated when I release a new version.
What I was hoping is something like what Google do with their Google Chrome app (may only be the beta version that does it not sure).
What I want to do is when the user launches my app, it can do a check to see if there is a new version available, and if so, just display a small message at the bottom to inform the user that there is a new version available for download. If they click it then the user will be taken straight to the app within the play store so they can commence the update.
How is this done? I've not managed to find anything for android, I've found a couple of things relating to iOS but obviously no good to me.
Thanks for any help you can provide.
Upvotes: 13
Views: 46016
Reputation: 2511
You can use google play core library to acheive this.
First you need to include the library in your gradle dependecies:
implementation "com.google.android.play:core-ktx:1.7.0"
Then you can use implement it like this:
class InAppUpdateManager @Inject constructor(
private val activity: Activity,
private val delegate: InAppUpdateDelegate
) {
private val appUpdateManager: AppUpdateManager by lazy {
AppUpdateManagerFactory.create(activity)
}
fun checkForUpdates() {
if (BuildConfig.IS_TEST_BACKEND) delegate.onUpdateNotAvailable()
else this.requestUpdate()
}
private fun requestUpdate() {
val updateStateListener = InstallStateUpdatedListener(delegate::onUpdatedStateChanged)
appUpdateManager.registerListener(updateStateListener)
appUpdateManager.appUpdateInfo
.addOnFailureListener(delegate::onUpdateInstallError)
.addOnSuccessListener(this::handleUpdateInfo)
}
private fun handleUpdateInfo(appUpdateInfo: AppUpdateInfo) {
when (appUpdateInfo.updateAvailability()) {
UpdateAvailability.UPDATE_AVAILABLE,
UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS -> {
delegate.onUpdateAvailable()
this.startInAppUpdate(appUpdateInfo)
}
else -> {
delegate.onUpdateNotAvailable()
}
}
}
private fun startInAppUpdate(appUpdateInfo: AppUpdateInfo) {
val updateType = when {
appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE) -> AppUpdateType.IMMEDIATE
appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE) -> AppUpdateType.FLEXIBLE
else -> null
}
if (updateType == null) {
delegate.onInAppUpdateNotAllowed()
return
}
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
updateType,
activity,
REQUEST_CODE_UPDATE
)
}
interface InAppUpdateDelegate {
fun onUpdateAvailable()
fun onInAppUpdateNotAllowed()
fun onUpdateNotAvailable()
fun onUpdatedStateChanged(installStatus: InstallState)
fun onUpdateInstallError(error: Exception)
}
companion object {
const val REQUEST_CODE_UPDATE = 69
}
}
Source: https://developer.android.com/guide/playcore/in-app-updates/kotlin-java
Upvotes: 1
Reputation: 111
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
va = String.valueOf(packageInfo.getLongVersionCode());
} else {
va = String.valueOf(packageInfo.versionCode);
}
//get last version from server like below code and comparison whit va
sv = new serviceApi(this);
sv.getVC("VERC_market", new setver.OnVC() {
@Override
public void onReceived(String vc) {
int vc1 = Integer.parseInt(vc);
int va1 = Integer.parseInt(va);
if (va1 < vc1) {
new AlertDialog.Builder(DemoPrimaryVocabGrouping.this)
.setMessage("hi pls give last version ")
.setPositiveButton("update", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent goToMarket = new Intent(Intent.ACTION_VIEW).setData(Uri
.parse("your app link in market"));
startActivity(goToMarket);
}
`enter code here` })
.setNegativeButton("no ", null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
});
Upvotes: -1
Reputation: 1297
You can do that with this new Android Official API https://developer.android.com/guide/app-bundle/in-app-updates
Upvotes: 7
Reputation: 771
Google has just made this a whole lot easier. See https://developer.android.com/guide/app-bundle/in-app-updates
Upvotes: 0
Reputation: 2751
I did it using Firebase Remote config. Here is my method which is called one time-
private void checkAndShowUpdateAvailableAlert() {
try {
String VERSION = "version";
String NEW_FEATURES = "newFeatures";
if (singleton.isUpdateAvailable()) {
FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
firebaseRemoteConfig.setConfigSettings(configSettings);
Map<String, Object> defaultValueHashMap = new HashMap<>();
defaultValueHashMap.put(VERSION, BuildConfig.VERSION_CODE);
defaultValueHashMap.put(NEW_FEATURES, "");
firebaseRemoteConfig.setDefaults(defaultValueHashMap);
long cacheExpiration = 3600; // 1 hour in seconds.
if (firebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
cacheExpiration = 0;
}
firebaseRemoteConfig.fetch(cacheExpiration)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
// showing update alert only one time
singleton.setUpdateAvailable(false);
firebaseRemoteConfig.activateFetched();
long remoteVersionCode = firebaseRemoteConfig.getLong(VERSION);
String newFeatures = firebaseRemoteConfig.getString(NEW_FEATURES);
Log.d(TAG, "Remote version: " + remoteVersionCode
+ ", New Features: " + newFeatures);
if (remoteVersionCode > BuildConfig.VERSION_CODE
&& newFeatures != null
&& !newFeatures.isEmpty()) {
contextUtility.showUpdateAlert(newFeatures);
}
} else {
Log.e(TAG, "Remote config fetch failed");
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
Steps-
I maintain two key value pairs in my firebase project-
1. newFeatures and
2. version
version is actually versionCode (integer) which is in sync with my latest build versionCode. When I release any new build, i update this value from firebase console.
In app, I check for this value (one time) and if it is greater, I show update alert to user. newFeatures is an additional key to display what's new
to user.
To check full source code- https://github.com/varunon9/SaathMeTravel
Upvotes: 2
Reputation: 1370
It might be useful for someone else. I tried this way
First create a class having couple of methods to launch play store and get app version code and version information this way
public class CheckForUpdate {
public static final String ACTION_APP_VERSION_CHECK="app-version-check";
public static void launchPlayStoreApp(Context context)
{
final String appPackageName = context.getPackageName(); // getPackageName() from Context or Activity object
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
public static int getRemoteVersionNumber(Context context)
{
int versionCode=0;
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
String version = pInfo.versionName;
versionCode=pInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
}
Second create another util class having sharedpreference methods to save and retrieve version code this way
public class PreferenceUtils {
// this is for version code
private final String APP_VERSION_CODE = "APP_VERSION_CODE";
private SharedPreferences sharedPreferencesAppVersionCode;
private SharedPreferences.Editor editorAppVersionCode;
private static Context mContext;
public PreferenceUtils(Context context)
{
this.mContext=context;
// this is for app versioncode
sharedPreferencesAppVersionCode=mContext.getSharedPreferences(APP_VERSION_CODE,MODE_PRIVATE);
editorAppVersionCode=sharedPreferencesAppVersionCode.edit();
}
public void createAppVersionCode(int versionCode) {
editorAppVersionCode.putInt(APP_VERSION_CODE, versionCode);
editorAppVersionCode.apply();
}
public int getAppVersionCode()
{
return sharedPreferencesAppVersionCode.getInt(APP_VERSION_CODE,0); // as default version code is 0
}
}
Finally you can use in your launcher activity or any other activity from where you want show alert dialog box to user to update app if its updated.
public class DashboardActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...........
//check whether app is first time launched
AppLaunchChecker.onActivityCreate(this);
alertAppUpdate();
}
Implement alertAppUpdate() method this way
private void alertAppUpdate()
{
int remoteVersionCode=CheckForUpdate.getRemoteVersionNumber(this);
PreferenceUtils preferenceUtils=new PreferenceUtils(this);
if(AppLaunchChecker.hasStartedFromLauncher(this))
{
preferenceUtils.createAppVersionCode(remoteVersionCode);
Log.i("First time","First time app is launched");
}
int existingVersionCode= preferenceUtils.getAppVersionCode();
if(remoteVersionCode>existingVersionCode)
{
/*
**
* app is updated, alert user to update app from playstore
* if app is updated then only save the version code in preferenceUtils
*
*/
AlertDialog.Builder dialogBuilder=AlertDialogBox.getAlertDialogBuilder(this,"Update available","Do you want to update your app now?");
dialogBuilder.setPositiveButton("Update Now", (dialogInterface, i) -> {
CheckForUpdate.launchPlayStoreApp(this);
Log.i("app update service","app is needed to update");
preferenceUtils.createAppVersionCode(remoteVersionCode);
});
dialogBuilder.setNegativeButton("Later",(dialogInterface,i)->{
});
dialogBuilder.show();
}
}
If any errors just let me know . Thank you.
Upvotes: 2
Reputation: 569
What we have used do this is as following ..
I send a cloud (having new app version in it) to app and handled it in app. While handling this cloud i check weather my current version and version in cloud are different than i show a pop-up to user periodically to update app from Google play..
Upvotes: 0
Reputation: 47
How to check there is new version of app is available on playstore, notify users to update old apps with new version in android and display yes or no to get them playstore. Just follow the instructions and put the attached code in your app to check the new version of app is available or not. This code check the app version each day if there is any new version update is available on playstore the a popup will appear on app launch for update.
if (newVersion > curVersion) {
/* Post a Handler for the UI to pick up and open the Dialog */
mHandler.post(showUpdate);
}
private Runnable showUpdate = new Runnable(){
public void run(){
new AlertDialog.Builder(MainActivity.this)
.setIcon(R.drawable.ic_launcher)
.setTitle("Update available")
.setMessage("An update for Live Share Tips is available on Play Store.")
.setNegativeButton("Update now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
easyTracker.send(MapBuilder.createEvent("App update",
"Update now", " ", null).build());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.appuonline.livesharetips"));
startActivity(intent);
}
})
.setPositiveButton("Later", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Cancel */
easyTracker.send(MapBuilder.createEvent("Update_Later",
"Update later", " ", null).build());
}
})
.show();
}
};
to download full code[url]:http://androidaone.com/11-2014/notify-users-update-app-new-version-available-playstore/
Upvotes: 0
Reputation: 6094
Sincerely, I think it's simply not worth the effort. My first recommendation is to forget it, as the Play Store will take care of the update notification.
If you really want to dedicate your time and effort, check this:
Upvotes: 6
Reputation: 82533
There is no API or service by when you can check with Google Play what the latest version of your app is.
Instead, you should maintain the latest version code on your server, and have your app check it periodically against its own version code. If the version code is higher on the server, then your app needs to be updated and you can tell the user accordingly.
Upvotes: 18