温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android 获取应用程序版本号

发布时间:2020-10-09 15:07:31 来源:网络 阅读:1268 作者:FergusJ 栏目:移动开发

功能:获取版本号

思路:版本号位置在AndroidManifest.xml文件中,需要找到一个类可以获取该位置的信息


需要使用到getPackageInfo和 PackageManager 这两个类。

一、getPackageInfo介绍和用法

介绍:PackageInfo类封装了从配置文件(AndroidManifest.xml)中获取的所有信息,描述了包内容的整体信息。

Overall information about the contents of a package. This corresponds to all of the information collected from AndroidManifest.xml.



二、PackageManager介绍和用法

介绍:PackageManager是一个检索当前已安装在设备上的相关应用程序包的各种信息的类。

Class for retrieving various kinds of information related to the application packages that are currently installed on the device. You can find this class through Context.getPackageManager


使用方法:

1.PackageManager对象的获取,Context对象提供了getPackageManager()方法。

2.getPackageInfo方法获取PackageInfo对象,该方法需要传递两个参数:应用包名packageName 和条件flags

  • packageName :The full name (i.e. com.google.apps.contacts) of the desired package.

  • flags: Additional option flags. Use any combination of GET_ACTIVITIES, GET_GIDS, GET_CONFIGURATIONS, GET_INSTRUMENTATION, GET_PERMISSIONS, GET_PROVIDERS, GET_RECEIVERS, GET_SERVICES, GET_SIGNATURES, GET_UNINSTALLED_PACKAGES to modify the data returned.


代码书写流程:

  1. 使用Context.getPackageManager获取PackageManager对象

  2. 使用PackageManager对象的getPackageInfo方法获取PackageInfo对象

  3. 获取PackageInfo的属性versionCode 或者其他信息


    /**
     * 获取版本号
     * 
     * @return 当前应用的版本名
     */
    public int getVersion() {
	try {
	    PackageManager manager = this.getPackageManager();
	    PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
	    String version = info.versionName;//版本的名称 用于显示在welcome界面下角
	    int versionCode = info.versionCode;//版本的code 用于比较升级
	    return versionCode;
	} catch (Exception e) {
	    e.printStackTrace();
	    return 0;
	}
    }


参考文章:

http://www.cnblogs.com/yeahui/archive/2012/10/20/2732429.html



向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI