Android 读取Manifest文件下的versionCode和versionName
首先在布局文件中放置两个TextView,这个就不多说了。
直接来说java文件中获取版本信息
1、首先获取PackageManager实例
PackageManager packageManager = getPackageManager();
2、获取应用程序的包名
String packageName = getPackageName();
3、获取packageInfo
packageInfo = packageManager.getPackageInfo(packageName, flag);
packageInfo = packageManager.getPackageInfo(packageName, flag);
其中packageName是包名,flag是一个选择的标志,是一个常量,可以以选择的包括GET_ACTIVITIES, GET_GIDS, GET_CONFIGURATIONS, GET_INSTRUMENTATION, GET_PERMISSIONS, GET_PROVIDERS, GET_RECEIVERS, GET_SERVICES, GET_SIGNATURES, GET_UNINSTALLED_PACKAGES 。具体可以参考android文档android.content.pm.PackageManager
4、获取版本信息
packageInfo.versionCode
packageInfo.versionName
结束,就四步就可以获取到Manifest文件中的版本信息
代码:
/**
* get Application version info
*
* @return 1、versionCode 2、versionName
*/
private String[] getVersionInfo() {
String[] version = new String[2];
//获取packageManager实例
PackageManager packageManager = getPackageManager();
// 获取包名
String packageName = getPackageName();
int flag = 0;
PackageInfo packageInfo = null;
// 获取packageInfo
try {
packageInfo = packageManager.getPackageInfo(packageName, flag);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
// 获取packageInfo中的版本信息等信息
if (packageInfo != null) {
version[0] = String.valueOf(packageInfo.versionCode);
version[1] = packageInfo.versionName;
Log.i("TAG", version[0]);
Log.i("TAG", version[1]);
}
return version;
}
/**
* get Application version info
*
* @return 1、versionCode 2、versionName
*/
private String[] getVersionInfo() {
String[] version = new String[2];
//获取packageManager实例
PackageManager packageManager = getPackageManager();
// 获取包名
String packageName = getPackageName();
int flag = 0;
PackageInfo packageInfo = null;
// 获取packageInfo
try {
packageInfo = packageManager.getPackageInfo(packageName, flag);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
// 获取packageInfo中的版本信息等信息
if (packageInfo != null) {
version[0] = String.valueOf(packageInfo.versionCode);
version[1] = packageInfo.versionName;
Log.i("TAG", version[0]);
Log.i("TAG", version[1]);
}
return version;
}
演示效果: