`

android获取versionName和versionCode

阅读更多
<TextView android:textSize="14.0sp" 
android:textColor="@color/lightblack" 
android:id="@+id/tv_version" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_marginBottom="20.0dip"
android:text="展示" />

 

public static String getVersion(Context context)//获取版本号
	{
		try {
			PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return context.getString(R.string.version_unknown);
		}
	}

 

	public static int getVersionCode(Context context)//获取版本号(内部识别号)
	{
		try {
			PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionCode;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
	}

 

2个获取方法都写在了CustomUtils.java文件中方便调用

具体的调用方法如下:

Textview tv_version;
tv_version=(TextView) this.findViewById(R.id.tv_version);
tv_version.setText(CustomUtils.getVersion(this));
//tv_version.setText(CustomUtils.getVersionCode(this)+"");
//之所以加“”是因为获取的versionCode是int类型的数据,加""直接转化为String,否则会报错

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics