每当app发布新版本时,需要发布到不同的应用市场,比如百度、豌豆荚等,为了统计app在每个市场的下载量、安装量等,需要给app打上唯一标识,美团的解决方案,以下是用Android Studio实现这一功能。
一、在AndroidManifest.xml里设置动态渠道变量

meta-data放在application下,上面的value值就是区分每个市场的标识。
private String getManifestChannel(Context context) {
try {
PackageManager pm = context.getPackageManager();
ApplicationInfo appInfo = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
return appInfo.metaData.getString("channel");
} catch (PackageManager.NameNotFoundException ignored) {
}
return "";
}
通过上面的代码即可获取渠道标识。
二、在build.gradle文件中配置productFlavors
productFlavors {
xiaomi {
manifestPlaceholders = [channel: "xiaomi"]
}
baidu {
manifestPlaceholders = [channel: "baidu"]
}
wandoujia {
manifestPlaceholders = [channel: "wandoujia"]
}
}
或者
productFlavors {
xiaomi {}
baidu {}
wandoujia {}
}
productFlavors.all {
flavor -> flavor.manifestPlaceholders = [channel: name]
}
三、执行Build->Generate Signed APK
到下图操作的时候,全选渠道,然后点击finish


如果要自定义apk名称,可以在build.gradle中配置如下代码
buildTypes {
//正式apk
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
// 自定义输出配置
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
// 输出apk名称为app_v1.0_baidu.apk
def fileName = "app_v${defaultConfig.versionName}_${variant.productFlavors[0].name}.apk"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
//测试apk
debugConfig {
// 自定义输出配置
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
// 输出apk名称为app_v1.0_baidu.apk
def fileName = "app_debug_v${defaultConfig.versionName}_${variant.productFlavors[0].name}.apk"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
}

如果需要为不同渠道定制不同的资源,如图片、文字信息等
右击项目->新建Android resource directory,选择资源保存的文件夹,如下图所示:

把工程的查看文件模式切换为Project(一般我们是使用Android文件模式的)


重新打包即可。
如果App内部有优先跳转到所发渠道的应用市场评价这个功能,那么就需要给不同的渠道配置不同的渠道信息,比如配置不同渠道的包名,则可以在build.gradle中自定义渠道包名属性。
productFlavors {
xiaomi {
buildConfigField "String", "CHANNEL_PACKAGE", "\"" + "com.xiaomi.market" + "\""
}
baidu {
buildConfigField "String", "CHANNEL_PACKAGE", "\"" + "com.baidu.appsearch" + "\""
}
wandoujia {
buildConfigField "String", "CHANNEL_PACKAGE", "\"" + "com.wandoujia.phoenix2" + "\""
}
}
通过Java代码BuildConfig.CHANNEL_PACKAGE获取。
网友评论