I decided to enhance my Android app so that it will show a little dialog with the newest features after starting.
If this dialog would show up after every start it would be very annoying.
The goal is to show it only when the user has just installed the app for the first time or after the app was upgraded to a newer version.
The solution is very simple:
- Get the current version of the app.
- Compare with the last version that the user has accepted.
- Show dialog if current version is newer.
- Store current version as accepted.
Storing the accepted version in the SharedPreferences
is very easy.
Getting the current version of the app is also easy, but it can be difficult to find out how to do it.
The API is somewhat hidden – you ask the package manager to give the PackageInfo
and there you can access the current versionName
.
Here is a snippet of the code from the onCreate()
in my main activity.
try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); String currentVersion = packageInfo.versionName; SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); String acceptedVersion = sharedPreferences.getString("pref_acceptedVersion", ""); if (currentVersion.compareTo(acceptedVersion) > 0) { Editor edit = sharedPreferences.edit(); edit.putString("pref_acceptedVersion", currentVersion); edit.commit(); showMessage(this, getResources().getString(R.string.new_version_message, currentVersion)); } } catch (NameNotFoundException e) { e.printStackTrace(); }
showMessage()
is a simple static method that shows a dialog.
private static void showMessage(Context context, int messageId) { showMessage(context, context.getResources().getString(messageId)); } private static void showMessage(Context context, String message) { new AlertDialog.Builder(context) .setMessage(message) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); }