Проблема компиляции Android Studio 3.0 (невозможно выбрать между конфигурациями)
Проблема с последней сборкой 3.0 (бета-версия 2) Мой проект имеет 1 подмодуль стороннего производителя, поэтому у меня есть доступ только к их build.gradle.
Мой проект имеет 3 вкуса, оснастка, уат, производство. У каждого есть 2 типа сборки: отладка и выпуск. Когда я пытаюсь собрать, я получаю это.
Error:Cannot choose between the following configurations of project :lp_messaging_sdk:
- debugApiElements
- debugRuntimeElements
- releaseApiElements
- releaseRuntimeElements
All of them match the consumer attributes:
- Configuration 'debugApiElements':
- Found com.android.build.api.attributes.BuildTypeAttr 'debug' but wasn't required.
- Found com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but wasn't required.
- Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
- Found org.gradle.api.attributes.Usage 'java-api' but wasn't required.
- Configuration 'debugRuntimeElements':
- Found com.android.build.api.attributes.BuildTypeAttr 'debug' but wasn't required.
- Found com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but wasn't required.
- Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
- Found org.gradle.api.attributes.Usage 'java-runtime' but wasn't required.
- Configuration 'releaseApiElements':
- Found com.android.build.api.attributes.BuildTypeAttr 'release' but wasn't required.
- Found com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but wasn't required.
- Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
- Found org.gradle.api.attributes.Usage 'java-api' but wasn't required.
- Configuration 'releaseRuntimeElements':
- Found com.android.build.api.attributes.BuildTypeAttr 'release' but wasn't required.
- Found com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' but wasn't required.
- Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
- Found org.gradle.api.attributes.Usage 'java-runtime' but wasn't required.
Я прочитал, что были проблемы с подмодулями и типами сборки, но затем прочитал, что это было исправлено. Вы должны были добавить те же типы сборки или что-то в подмодули build.gradle, а затем добавить
buildTypeMatching 'debug', 'release'
Однако когда я делаю это, я получаю эту ошибку,
Error:Could not select value from candidates [debug, release] using AlternateDisambiguationRule.BuildTypeRule.
apply plugin: 'com.android.application'
android {
repositories {
flatDir {
dirs project(':lp_messaging_sdk').file('aars')
}
}
// Android parameters
compileSdkVersion = 26
buildToolsVersion = '26.0.1'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dexOptions {
preDexLibraries true
}
defaultConfig {
minSdkVersion 19
versionName buildName
versionCode buildVersion
multiDexEnabled true
resConfigs "en", "fr", "fr-rCA"
}
signingConfigs {
release {
}
}
flavorDimensions "default"
productFlavors {
snap {
ext.betaDistributionGroupAliases = "INTERNAL"
ext.betaDistributionReleaseNotesFilePath = 'changelog.txt'
ext.betaDistributionNotifications = true
dimension "default"
}
uat {
ext.betaDistributionGroupAliases = "INTERNAL"
ext.betaDistributionNotifications = true
}
production {
}
}
buildTypes {
debug {
versionNameSuffix createVersionNameSuffix()
applicationIdSuffix '.debug'
minifyEnabled true
testCoverageEnabled false
buildConfigField "String", "PLAY_STORE_VERSION_NAME", '"' + PLAY_STORE_VERSION_NAME + '"'
// Workaround for : https://code.google.com/p/android/issues/detail?id=212882
proguardFiles fileTree(dir: 'proguard', include: ['*.pro']).asList().toArray()
ext.enableCrashlytics = false
}
release {
versionNameSuffix createVersionNameSuffix()
minifyEnabled true
testCoverageEnabled = false
signingConfig signingConfigs.release
buildConfigField "String", "PLAY_STORE_VERSION_NAME", '"' + PLAY_STORE_VERSION_NAME + '"'
// Workaround for : https://code.google.com/p/android/issues/detail?id=212882
proguardFiles fileTree(dir: 'proguard', include: ['*.pro']).asList().toArray()
}
}
//Used to ignore duplicated entries added to meta-inf
packagingOptions {
exclude 'LICENSE.txt'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice'
exclude 'META-INF/notice.txt'
exclude 'META-INF/services/javax.annotation.processing.Processor'
}
dexOptions {
javaMaxHeapSize "2048m"
dexInProcess true
}
lintOptions {
abortOnError true
xmlReport true
htmlReport true
disable 'MissingTranslation', 'InvalidPackage'
disable 'GradleCompatible', 'GradleCompatible'
disable 'NewApi', 'NewApi'
disable 'GradleDependency'
disable 'UnusedResources'
disable 'IconDensities'
disable 'TypographyDashes'
disable 'ContentDescription'
htmlOutput file("$project.buildDir/reports/lint/lint-result.html")
xmlOutput file("$project.buildDir/reports/lint/lint-result.xml")
}
testOptions {
unitTests.returnDefaultValues = true
}
}
greendao {
schemaVersion 13
targetGenDir 'src/main/java/'
}
ext.betaDistributionReleaseNotes = System.getenv("CHANGELOG")
def createVersionNameSuffix() {
def buildNumber = System.env.BUILD_NUMBER
def buildTimestamp = new Date().format('HH:mm dd/MM/yy')
return buildNumber ? " ($buildNumber)" : " ($buildTimestamp)"
}
def getBuildVersionFromName(String buildName) {
List data = buildName.tokenize(".")
String resultString = "19";
for (String s : data) {
resultString += s;
}
if (System.env.BUILD_NUMBER) {
resultString += System.env.BUILD_NUMBER
}
return Integer.parseInt(resultString);
}
//Verify the app before creating a Pull Request
task verifyPR
verifyPR.dependsOn('clean')
verifyPR.dependsOn('lint')
verifyPR.dependsOn('checkstyle')
verifyPR.dependsOn('pmd')
verifyPR.dependsOn('testSnapDebugUnitTest')
dependencies {
// Android Dependencies
compile 'com.android.support:appcompat-v7:26.0.1'
compile 'com.android.support:design:26.0.1'
compile 'com.android.support:recyclerview-v7:26.0.1'
compile 'com.android.support:multidex:1.0.2'
// Dagger Dependencies
apt 'com.google.dagger:dagger-compiler:2.11'
compile 'org.glassfish:javax.annotation:10.0-b28'
compile 'com.google.dagger:dagger:2.11'
// Rx Dependencies
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.3.0'
compile 'com.jakewharton.rxbinding:rxbinding-appcompat-v7:0.4.0'
compile 'com.jakewharton.rxbinding:rxbinding-support-v4:0.4.0'
compile 'com.squareup.whorlwind:whorlwind:1.0.1'
compile 'com.tbruyelle.rxpermissions:rxpermissions:0.9.4@aar'
compile 'com.jenzz:RxAppState:2.0.0'
// Tools
compile 'com.crashlytics.sdk.android:crashlytics:2.6.5'
// ButterKnife
compile 'com.jakewharton:butterknife:8.4.0'
// Google Maps
compile 'com.google.android.gms:play-services-maps:11.0.4'
compile "com.google.android.gms:play-services-analytics:11.0.4"
compile 'com.google.android.gms:play-services-location:11.0.4'
compile 'com.google.android.gms:play-services-places:11.0.4'
compile 'com.google.android.gms:play-services-gcm:11.0.4'
// Geofence
compile('pl.charmas.android:android-reactive-location:0.10@aar') {
transitive = true
}
// Retrofit
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
// OKHTTP
compile 'com.squareup.okhttp:okhttp-urlconnection:2.7.5'
// Libphonenumber
compile 'com.googlecode.libphonenumber:libphonenumber:7.3.2'
// UI
compile 'com.tubb.smrv:swipemenu-recyclerview:5.0.2'
// EventBus
compile 'org.greenrobot:eventbus:3.0.0'
// Database
compile 'org.greenrobot:greendao:3.2.0'
// Chuck HTTP Inspector
debugCompile 'com.readystatesoftware.chuck:library:1.0.4'
releaseCompile 'com.readystatesoftware.chuck:library-no-op:1.0.4'
// ViewPager Indicator
compile 'com.github.JakeWharton:ViewPagerIndicator:2.4.1'
// Amplitude
compile 'com.amplitude:android-sdk:2.13.2'
// TESTS
testCompile 'junit:junit:4.12'
testCompile "org.mockito:mockito-core:1.10.19"
testCompile "org.powermock:powermock-module-junit4:1.6.5"
testCompile "org.powermock:powermock-module-junit4-rule:1.6.4"
testCompile "org.powermock:powermock-api-mockito:1.6.5"
testCompile "org.powermock:powermock-classloading-xstream:1.6.4"
compile project(':lp_messaging_sdk')
}
А вот и сторонняя библиотека build.gradle
apply plugin: 'com.android.library'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
minSdkVersion 14
targetSdkVersion 26
versionCode 250
versionName "2.5.0"
}
flavorDimensions "default"
productFlavors {
snap {
ext.betaDistributionGroupAliases = "INTERNAL"
ext.betaDistributionReleaseNotesFilePath = 'changelog.txt'
ext.betaDistributionNotifications = true
dimension "default"
}
uat {
ext.betaDistributionGroupAliases = "INTERNAL"
ext.betaDistributionNotifications = true
}
production {
}
}
signingConfigs {
release {
}
}
buildTypeMatching 'snap', 'debug', 'release'
buildTypes {
debug {
applicationIdSuffix '.debug'
minifyEnabled true
testCoverageEnabled false
buildConfigField "String", "PLAY_STORE_VERSION_NAME", '"' + PLAY_STORE_VERSION_NAME + '"'
// Workaround for : https://code.google.com/p/android/issues/detail?id=212882
proguardFiles fileTree(dir: 'proguard', include: ['*.pro']).asList().toArray()
ext.enableCrashlytics = false
}
release {
minifyEnabled true
testCoverageEnabled = false
signingConfig signingConfigs.release
buildConfigField "String", "PLAY_STORE_VERSION_NAME", '"' + PLAY_STORE_VERSION_NAME + '"'
// Workaround for : https://code.google.com/p/android/issues/detail?id=212882
proguardFiles fileTree(dir: 'proguard', include: ['*.pro']).asList().toArray()
}
}
defaultConfig {
consumerProguardFiles 'proguard.cfg'
}
repositories {
flatDir {
dirs 'aars'
}
}
lintOptions {
disable 'InvalidPackage'
}
}
dependencies {
compile 'com.android.support:appcompat-v7:26.0.1'
compile 'com.android.support:design:26.0.1'
compile 'com.android.support:recyclerview-v7:26.0.1'
compile 'com.android.support:percent:26.0.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.neovisionaries:nv-websocket-client:1.31'
compile 'com.squareup.okhttp3:okhttp:3.8.0'
compile(name: 'infra', ext: 'aar')
compile(name: 'messaging', ext: 'aar')
compile(name: 'messaging_ui', ext: 'aar')
compile(name: 'ui', ext: 'aar')
}
Кто-нибудь знает, как я могу решить эту проблему? Спасибо
11 ответов
Пытаться
implementation project(path: ':lp_messaging_sdk', configuration: 'default')
Замечания:
Вы можете избежать этой ошибки, обновив Gradle до 4.3
проверь это.
Пояснение:
Использование зависимостей позволяет легко определить и указать, что использовать в подпроекте.
В моем ответе мы использовали конфигурацию по умолчанию, и это будет публиковать и показывать только вариант "релиз" другим проектам и модулям Android.
Предположим, вам нужно включить этот аромат только с демо-ароматом или с релиз-ароматом, это будет выглядеть так:
configurations {
// Initializes placeholder configurations that the Android plugin can use when targeting
// the corresponding variant of the app.
demoDebugCompile {}
fullReleaseCompile {}
...
}
dependencies {
// If the library configures multiple build variants using product flavors,
// you must target one of the library's variants using its full configuration name.
demoDebugCompile project(path: ':lp_messaging_sdk', configuration: 'demoDebug')
fullReleaseCompile project(path: ':lp_messaging_sdk', configuration: 'fullRelease')
...
}
Итак, в вашем случае вы можете использовать свои варианты сборки, и это то, что появилось в журнале ошибок.
Cannot choose between the following configurations of project :lp_messaging_sdk
И это значит, что ваш lp_messaging_sdk
иметь различные конфигурации сборки:
- debugApiElements
- debugRuntimeElements
- releaseApiElements
- releaseRuntimeElements
И android-studio говорит вам, что "я не могу выбрать одну конфигурацию из этих различных, вы бы определили ее для меня?"
Вы можете прочитать больше здесь.
Ошибка: Невозможно выбрать одну из следующих конфигураций проекта.......
Могут быть проблемы с написанием в gradle. Когда я перешел на следующую формулировку, такой ошибки нет
// скомпилировать проект (':MPChartLib')
implementation project(':MPChartLib')
Может быть, когда ссылка зависит от других модулей, должны быть написаны в этой реализации
Если вы используете плагин android-apt для обработки аннотаций, попробуйте удалить этот плагин и заменить все apt some_dependency
ссылки с annotationProcessor some_dependency
как предложено в руководстве по миграции для Android Gradle Plugin 3.0.0.
Для AndroidStudio 3.0+, mainMoudle имеет buildTypes и buildTypes так же, как libModule buildTypes и buildTypes, он хотел бы:
mainModule:
buildTypes {
release {
buildConfigField "boolean", "LOG_DEBUG", "false"
zipAlignEnabled true
shrinkResources true
minifyEnabled true
proguardFiles 'proguard-rules.pro'
}
debug {
buildConfigField "boolean", "LOG_DEBUG", "true"
zipAlignEnabled true
shrinkResources false
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug2{
}
}
libModule:
buildTypes {
release {
}
debug {
}
debug2{
}
}
или вы можете использовать соответствующие обратные ссылки решить этот клик
Когда я обновил свой проект с уровня API 23 до 27 и Gradle до 3.1, эта ошибка приходит, что
Msgstr "Невозможно выбрать между различными конфигурациями".
Так что решить эту проблему.
замените проект компиляции (':your projectName')
с реализацией проекта (':projectname')
в Gradle это решить проблему.
Эта ошибка также возникает, если следующее НЕ верно:
Включив модуль B в A, все продукты, которые существуют в A, должны существовать в B.
build.gradle (: приложение) или (: модуль-A)
android {
flavorDimensions "dimen"
productFlavors {
someProduct {
dimension "dimen"
}
}
}
dependencies {
api project(path: ':module-B')
}
Так
someProduct
должен существовать в B
build.gradle (: модуль-B)
android {
flavorDimensions "dimen"
productFlavors {
someProduct {
dimension "dimen"
}
}
}
GL
В моем аналогичном случае решение было:
build.gradle:
android {
defaultConfig {
// because I have two project flavors in that library
missingDimensionStrategy 'project', 'myProjectName'
// because I have a "full" and a "debug" flavor in that library
missingDimensionStrategy 'mode', 'full'
}
buildTypes {
debug { ... }
release { ... }
}
}
dependencies {
// because the project(path:'', configuration:'') did not work in this case
implementation project(':myModuleName1')
implementation project(':myModuleName2')
}
Возможно, это поможет другим столкнуться с подобной проблемой.
Для меня эта же ошибка возникает в Android Studio 3.5.2, но по другой причине. Я пытался добавить модуль приложения в качестве библиотеки.
Я решил это, просто преобразовав модуль приложения в модуль библиотеки.
В этих случаях, когда в вашем основном проекте используются модули или библиотечные модули (AAR), которые имеют размерности, ваше приложение не знает, какой из них использовать. Вы должны использовать missingDimensionStrategy в defaultConfig блоке build.gradle файла вашего приложения , чтобы указать аромат по умолчанию. Например :
missingDimensionStrategy 'dimension', 'flavor1', 'flavor2'
Пожалуйста, проверьте эту ссылку для получения более подробной информации.
Моя проблема заключалась в том, что я переименовывал имя выходного файла (и путь)
После того, как я удалил код gradle, который менял имя, путь к моему решению был проще.
Если вы используете сложную настройку, в которой есть модуль, а затем несколько подмодулей и т. Д., Тогда вам нужно добавить варианты сборки в модуль (скажем, верхний модуль), а затем в подмодуль и другие модули, которые могут использовать ваш модуль. Вы не можете напрямую добавить в подмодуль, иначе студия Android запутается, какой из них выбрать.
Чтобы привести пример, скажем, есть snapDebug для подмодуля в качестве варианта сборки, теперь он должен быть объединен с snapDebug для верхнего модуля или snapDebug модуля, использующего его. Если snapDebug отсутствует ни в одном из них, студия Android запутается, какой из них выбрать с другим. Отсюда и ошибка в последних сборках студии Android.
Надеюсь, это поможет понять проблему и ее решение.