最近用到多渠道打包,记一下android studio 原生打包配置(Android studio 版本4.2.1)
1:配置清单文件,在application 中配置meta-data,和Activity平级,如下图
<!--多渠道打包用-->
<meta-data
android:name="CHANNEL"
android:value="${CHANNEL_VALUE}" />
2:在app build.gradle中android节点里配置productFlavors闭包,具体如下图
productFlavors {
huawei {
manifestPlaceholders = [CHANNEL_VALUE: "51"]
}
xiaomi {
manifestPlaceholders = [CHANNEL_VALUE: "52"]
}
oppo {
manifestPlaceholders = [CHANNEL_VALUE: "53"]
}
yingyongbao {
manifestPlaceholders = [CHANNEL_VALUE: "54"]
}
wandoujia {
manifestPlaceholders = [CHANNEL_VALUE: "55"]
}
vivo {
manifestPlaceholders = [CHANNEL_VALUE: "56"]
}
}
3:配置:flavorDimensions
flavorDimensions "versionCode"
4:配置打包输出
//自动打包配置
applicationVariants.all { variant ->
variant.outputs.all {
def fileName = "demo_${variant.productFlavors[0].name}_${defaultConfig.versionName}.apk"
outputFileName = fileName
}
}
5:使用相关配置,请求接口的时候当作参数传递给服务器,用来统计渠道来源
private String getChannel(Context context) {
ApplicationInfo appInfo = null;
try {
appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
int msg = appInfo.metaData.getInt("CHANNEL",0);
return String.valueOf(msg);
}
注意:我配置的这个参数是int类型的,所以用appInfo.metaData.getInt(“CHANNEL”,0)获取,具体看你配置的数据类型是什么就用打点调用相关参数就行,key是清单文件配置的,打包的话看你自己需求,打那个选取那个就行
完整 build.gradle配置如下
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
flavorDimensions "versionCode"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
//自动打包配置
applicationVariants.all { variant ->
variant.outputs.all {
def fileName = "demo_${variant.productFlavors[0].name}_${defaultConfig.versionName}.apk"
outputFileName = fileName
}
}
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
productFlavors {
huawei {
manifestPlaceholders = [CHANNEL_VALUE: "51"]
}
xiaomi {
manifestPlaceholders = [CHANNEL_VALUE: "52"]
}
oppo {
manifestPlaceholders = [CHANNEL_VALUE: "53"]
}
yingyongbao {
manifestPlaceholders = [CHANNEL_VALUE: "54"]
}
wandoujia {
manifestPlaceholders = [CHANNEL_VALUE: "55"]
}
vivo {
manifestPlaceholders = [CHANNEL_VALUE: "56"]
}
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4'
}
结束!