Android网络请求头添加app版本信息

相信很多项目都有这样的需求,给请求头添加用户当前应用版本的信息,直接上代码如下:

一,获取当前应用版本名 (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;

}

二、获取当前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;

}

}

请求头添加应用版本信息用法:

Request request  = new Request.Builder().addHeader("App-Version",versionUtil.getVerCode(getApplicationContext()).build();


你可能感兴趣的:(Android网络请求头添加app版本信息)