正常来说我们在自己的app应用中的欢迎页和设置中心会显示当前app的版本号,代码如下:
//获取自己应用内部的版本号
public static int getVersionCode(Context context) {
PackageManager manager = context.getPackageManager();
int code = 0;
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
code = info.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return code;
}
//获取自己应用内部的版本名
public static String getVersionName(Context context) {
PackageManager manager = context.getPackageManager();
String name = null;
try {
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
name = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return name;
}
但是如果我们要获取手机中已安装的其他应用的版本名和版本号,也可以采用同样的代码,但是需要拿到应用的包名,代码如下:
//获取其他应用的版本号
public static int getVersionCode(Context context,String packageName) {
PackageManager manager = context.getPackageManager();
int code = 0;
try {
PackageInfo info = manager.getPackageInfo(packageName, 0);
code = info.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return code;
}
//获取其他应用的版本名
public static String getVersionName(Context context,String packageName) {
PackageManager manager = context.getPackageManager();
String name = null;
try {
PackageInfo info = manager.getPackageInfo(packageName, 0);
name = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return name;
}