Application Scenario:
1. Display the version number of the application in the interface;
2, the user launches the application, backstage to determine whether the application is the latest version.
All of the above scenarios need to automatically get the version number of the application in the program.
Introduction of Ideas:
In Android, The version number of the application is configured in the Androidmanifest.xml file, and the PackageInfo class encapsulates all the information obtained from the configuration file, describing the overall information of the package content, so you can use the Versionname property of the PackageInfo object to get the application's Version number.
How do I get the PackageInfo object? can be obtained by Packagemanager object. Packagemanager is a class that retrieves various information about a related application package that is currently installed on a device. The Getpackageinfo method in the Packagemanager object can get the PackageInfo object, which requires two parameters to be passed: Application package name and condition. Typically, an application's package name can be obtained by the Getpackagename () method of the activity or context (the activity inherits from the context), and the addition can have many settings, usually set to 0.
Finally, the Packagemanager object is fetched, and the context object provides a Getpackagemanager () method to get the object.
In summary, the template code is as follows: (Note that the method that is encapsulated here is in an activity, so use this directly instead of the context object)
/**
* Get version number
* @return version number of the current application
*/
Public String getversion () {
try {
Packagemanager manager = This.getpackagemanager ();
PackageInfo info = manager.getpackageinfo (this.getpackagename (), 0);
String Version = Info.versionname;
Return this.getstring (r.string.version_name) + version;
catch (Exception e) {
E.printstacktrace ();
Return this.getstring (R.string.can_not_find_version_name);
}
}