每當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文件模式的)
切換Android文件模式為Project
把資源文件復制到對應渠道
重新打包即可。
如果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獲取。