Android 工作室: 为什么在 AndroidManifest.xml 和 build.gradle 中都指定 minSdkVersion 和 targetSdkVersion?

我刚刚发现了 Android 工作室的一些奇怪之处: 它在 build.gradle文件中有一些配置选项,可以覆盖在 AndroidManifest.xml文件中指定的内容。

例如,我在 build.gradle中有以下几行:

android {
compileSdkVersion 18
buildToolsVersion "18.1.1"


defaultConfig {
minSdkVersion 10
targetSdkVersion 10
}
...
}

它覆盖了 AndroidManifest.xml中相应的标记:

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8"/>

我真的不喜欢有相同的设置分布在两个不同的文件,所以我想知道,如果我可以安全地删除它无论是从 build.gradleAndroidManifest.xml和它更有意义的地方,保持它。

39054 次浏览

Gradle overrides the manifest values, and I prefer to update the build.gradle file rather than the manifest. Probably this is the right way using Gradle. Gradle supports product flavours which can be controlled via an IDE and those product flavors can change many things in our Manifest like package name, version code, version name, target SDK and many other. Then by one click in Android Studio you can change many properties and generate another apk.

You can leave the manifest as it is and do all configuration in build.gradle. You can safely remove

<uses-sdk></uses-sdk>

from manifest as well as version codes.

From the Android docs:

Note: If your app defines the app version directly in the element, the version values in the Gradle build file will override the settings in the manifest. Additionally, defining these settings in the Gradle build files allows you to specify different values for different versions of your app. For greater flexibility and to avoid potential overwriting when the manifest is merged, you should remove these attributes from the element and define your version settings in the Gradle build files instead.

https://developer.android.com/studio/publish/versioning.html#appversioning