相信很多項目都有這樣的需求呻纹,給請求頭添加用戶當(dāng)前應(yīng)用版本的信息,直接上代碼如下:
一荔烧,獲取當(dāng)前應(yīng)用版本名 (versionName)
/**
*得到版本名manifest.vml version Name
*@paramcontext
*@return
*/
public static String getVersion(Context context){
String versionName ="";
try{
PackageManager packageManager = context.getPackageManager();
//得包名
String packageName = context.getPackageName();
//包的信息蛔琅,一個包有多少個activity,
PackageInfo packageInfo = packageManager.getPackageInfo(packageName,0);
versionName = packageInfo.versionName;
}catch(PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
二符衔、獲取當(dāng)前App版本號
/**
*獲取本地apk版本號
*@return
*/
public static int getVerCode(Context context) {
intverCode =0;
try{
PackageManager packageManager = context.getPackageManager();
//得包名
String packageName = context.getPackageName();
//包的信息,一個包有多少個activity,
PackageInfo packageInfo = packageManager.getPackageInfo(packageName,0);
verCode = packageInfo.versionCode;
L.e(verCode+"code");
}catch(PackageManager.NameNotFoundException e) {
L.e(e.getMessage());
}
return verCode;
}
三丈屹、我們將獲取版本信息封裝成工具類 VersionUtil
public class versionUtil {
/**
*得到版本名manifest.vml version Name
*@paramcontext
*@return
*/
public static String getVersion(Context context){
String versionName ="";
try{
PackageManager packageManager = context.getPackageManager();
//得包名
String packageName = context.getPackageName();
PackageInfo packageInfo = packageManager.getPackageInfo(packageName,0);
versionName = packageInfo.versionName;
}catch(PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
/**
*獲取本地apk版本號
*@return
*/
public static int getVerCode(Context context) {
intverCode =0;
try{
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();
PackageInfo packageInfo = packageManager.getPackageInfo(packageName,0);
verCode = packageInfo.versionCode;
L.e(verCode+"code");
}catch(PackageManager.NameNotFoundException e) {
L.e(e.getMessage());
}
return verCode;
}
}
請求頭添加應(yīng)用版本信息用法:
Request request? = new Request.Builder().addHeader("App-Version",versionUtil.getVerCode(getApplicationContext()).build();