Android Plugin DSL Reference 参考文档 :
ProductFlavor 参考文档 : com.android.build.gradle.internal.dsl.ProductFlavor.html
ProductFlavor#manifestPlaceholders
配置 , 用于配置 manifest 的占位符 , 该配置项是 Map<String, Object>
类型的 ;
在 build.gradle 的 ProductFlavor defaultConfig
配置项中 , 设置清单文件占位符属性 , 为其设置一个 Map<String, Object>
类型的属性 ;
代码示例 :
android {
defaultConfig {
manifestPlaceholders = [name: 'Tom']
}
完整代码 :
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 31
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.ad_id_test"
minSdkVersion 18
targetSdkVersion 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
manifestPlaceholders = [name: 'Tom']
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
清单文件配置 : 在下面的 meta-data 标签中 , 使用了 {name} 引用了 build.gradle 中定义的 manifestPlaceholders = [name: 'Tom'] , 在合并清单文件时 , 会自动使用 Tom 替换上述 {name} 引用 ;
<meta-data android:name="student" android:value="${name}" />
完整 AndroidManifest.xml 清单文件配置 :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ad_id_test">
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AD_ID_Test">
<meta-data android:name="student" android:value="${name}" />
<activity android:name=".MainActivity"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
将 AndroidManifest.xml 清单文件 切换到 Merged Manifest 模式 , 可以看到合并后的 清单文件 , 其中 <meta-data>
标签 , 由
<meta-data
android:name="student"
android:value="${name}" />
变成了
<meta-data
android:name="student"
android:value="Tom" />
样式 , ${name}
被 Tom
替换了 ;