This post will briefly show how you can read you application’s version programmatically and then show in the app’s preferences.
The version is defined in the app’s Manifest.xml file.
1 2 3 4 |
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="foo" android:versionCode="1" android:versionName="1.0" > |
Add a preference that contains the version.
1 2 3 4 |
<Preference android:key="@string/version_key" android:summary="@string/version_summary" android:title="@string/version_title" /> |
Extend the fragment and update the version preference with the app’s version name.
1 2 3 4 5 6 7 8 9 10 |
public class PrefFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.prefs); findPreference(getString(R.string.version_key)).setSummary( getString(R.string.version_summary, AppUtil.getApplicationVersionName(getActivity()))); } } |
Helper class for fetching the app’s version from code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class AppUtil { public static String getApplicationVersionName(Context ctx) { String result = ""; try { result = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { } return result; } public static int getApplicationVersion(Context ctx) { int result = 1; try { result = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionCode; } catch (NameNotFoundException e) { } return result; } } |