使用包管理器
package com.liunan.myfirstapp.util;import android.content.Context;import android.content.pm.ApplicationInfo;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;/*** Created by 劉楠 on 2016-03-22.*/public class PackageUtils {/*** 擷取版本名稱* @param context 上下文* @return 版本名稱*/public static String getVersionName(Context context){//擷取包管理器PackageManager pm = context.getPackageManager();//擷取包資訊try {PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(),0);//返回版本號碼return packageInfo.versionName;} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}return null;} /*** 擷取版本號碼* @param context 上下文* @return 版本號碼*/public static int getVersionCode(Context context){//擷取包管理器PackageManager pm = context.getPackageManager();//擷取包資訊try {PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(),0);//返回版本號碼return packageInfo.versionCode;} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}return 0;}/*** 擷取App的名稱* @param context 上下文* @return 名稱*/public static String getAppName(Context context){PackageManager pm = context.getPackageManager();//擷取包資訊try {PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(),0);//擷取應用 資訊ApplicationInfo applicationInfo = packageInfo.applicationInfo;//擷取albelResint labelRes = applicationInfo.labelRes;//返回App的名稱return context.getResources().getString(labelRes);} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}return null;}}
下面給大家分享一段代碼介紹Android擷取App版本號碼和版本名
/ 以下是獲得版本資訊的工具方法
//版本名public static String getVersionName(Context context) {return getPackageInfo(context).versionName;}//版本號碼public static int getVersionCode(Context context) {return getPackageInfo(context).versionCode;}private static PackageInfo getPackageInfo(Context context) {PackageInfo pi = null;try {PackageManager pm = context.getPackageManager();pi = pm.getPackageInfo(context.getPackageName(),PackageManager.GET_CONFIGURATIONS);return pi;} catch (Exception e) {e.printStackTrace();}return pi;}
有關Android擷取應用版本號碼與版本名稱的知識,小編就給大家介紹到這裡,希望對大家有所協助!