How to get the version of your Android application from AndroidManifest.xml?

  Uncategorized

There are two parts of the version in AndroidManifest.xml.

  • android:versionCode
  • android:versionName

In your AndroidManifest.xml the versionCode is a number, and every version you want to submit to google play needs to have a higher number then the last. VersionName is just a string, and can be anything you want it to be. In VersionName you can define your app as “1.0” or “2.5.1.12982” or “Test Version” or whatever.

To get the android:versionCode and the android:versionName you can use the following code snippet where context is your actual context. If you execute this code in your Activity you can remove the “context.” from “context.getPackageManager()”. Because the Activity is a indirect Subclasses of Context.

Context context = getApplicationContext();
PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
String versionName = pInfo.versionName;
String versionCode = pInfo.versionCode;

Note: Other known Subclasses of Context are:

AbstractInputMethodService
AccessibilityService
AccountAuthenticatorActivity
ActionBarActivity
Activity
ActivityGroup
AliasActivity
AppCompatActivity
Application
BackupAgent
BackupAgentHelper
CarrierMessagingService
DreamService
ExpandableListActivity
FragmentActivity
HostApduService
InputMethodService
IntentService
IsolatedContext
JobService
LauncherActivity
ListActivity
MediaBrowserService
MediaRouteProviderService
MockApplication
MultiDexApplication
MutableContextWrapper
NativeActivity
NotificationCompatSideChannelService
NotificationListenerService
OffHostApduService
PreferenceActivity
PrintService
RecognitionService
RemoteViewsService
RenamingDelegatingContext
Service
SettingInjectorService
SpellCheckerService
TabActivity
TestActivity
TextToSpeechService
TvInputService
VoiceInteractionService
VoiceInteractionSessionService
VpnService
WallpaperService

If you are not in in a class that is a subclass of Context you have to identify your context to get the version from your AndroidManifest.xml.