安卓工具类之 app 获取版本渠道信息工具类
*/
public static String getAppVersionName(Context pContext) {
String _VersionName = "";
try {
PackageManager _PM = pContext.getPackageManager();
PackageInfo _PInfo = _PM.getPackageInfo(pContext.getPackageName(), 0);
_VersionName = _PInfo.versionName;
if (_VersionName == null || _VersionName.length() <= 0) {
return "";
}
} catch (Exception e) {
e.printStackTrace();
}
return _VersionName;
}
/**
获取 APP 版本号
@param pContext Context
@return AppVersionCode
*/
public static int getAppVersionCode(Context pContext) {
int _VersionCode = 0;
try {
PackageManager _PM = pContext.getPackageManager();
PackageInfo _PInfo = _PM.getPackageInfo(pContext.getPackageName(), 0);
_VersionCode = _PInfo.versionCode;
} catch (Exception e) {
e.printStackTrace();
}
return _VersionCode;
}
/**
获取 APP 的 ChannelId
@param pContext
@return
*/
public static synchronized int getAppChannelId(Context pContext){
int __ChannelId = 0;
String _ChannelId = AppConfig.getAppChannelId(pContext);
try {
if (TextUtils.isEmpty(_ChannelId)){
_ChannelId = getChannelFromApk(pContext);
if (TextUtils.isEmpty(_ChannelId)){
_ChannelId = FileAssetsUtil.getStringFromAssert(pContext, "cn");
if (!TextUtils.isEmpty(_ChannelId)){
AppConfig.setAppChannelId(pContext, _ChannelId);
}
}else {
AppConfig.setAppChannelId(pContext, _ChannelId);
}
}
if (!TextUtils.isEmpty(_ChannelId)){
__ChannelId = Integer.parseInt(_ChannelId);
}else {
__ChannelId = 0;
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return __ChannelId;
}
/**
获取 APP 的 Channel2Id
@param pContext
@return
*/
public static synchronized int getAppChannel2Id(Context pContext){
int __Channel2Id = 0;
String _Channel2Id = AppConfig.getAppChannel2Id(pContext);
try {
if (TextUtils.isEmpty(_Channel2Id)){
_Channel2Id = FileAssetsUtil.getStringFromAssert(pContext, "cn2");
if (!TextUtils.isEmpty(_Channel2Id)){
AppConfig.setAppChannel2Id(pContext, _Channel2Id);
}
}
if (!TextUtils.isEmpty(_Channel2Id)){
__Channel2Id = Integer.parseInt(_Channel2Id);
}else {
__Channel2Id = 0;
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return __Channel2Id;
}
/**
从 apk 中获取版本信息
@param pContext
@return
*/
private static String getChannelFromApk(Context pContext) {
//从 apk 包中获取
ApplicationInfo _AppInfo = pContext.getApplicationInfo();
String _SourceDir = _AppInfo.sourceDir;
//默认放在 META-INF/里, 所以需要再拼接一下
String _Key = "META-INF/" + CHANNEL_KEY;
String _Ret = "";
ZipFile _ZipFile = null;
try {
_ZipFile = new ZipFile(_SourceDir);
Enumeration<?> _Entries = _ZipFile.entries();
while (_Entries.hasMoreElements()) {
ZipEntry _ZipEntry = ((ZipEntry) _Entries.nextElement());
String _EntryName = _ZipEntry.getName();
if (_EntryName.startsWith(_Key)) {
_Ret = _EntryName;
break;
}
}
评论