Подтвердить что ты не робот

Ошибка Android Studio 3.0. Перенастройка конфигураций зависимостей для локальных модулей

Недавно я установил последнюю версию Canary для Android Studio, которая в настоящее время использует плагин Android Gradle 3.0.0-alpha4.

Теперь я получаю сообщение об ошибке:

Error:Failed to resolve: Could not resolve project :MyLib.
Required by:
project :app

Я читал: Перенос конфигураций зависимостей для локальных модулей

dependencies 

{

// This is the old method and no longer works for local
// library modules:
// debugCompile project(path: ':foo', configuration: 'debug')
// releaseCompile project(path: ':foo', configuration: 'release')

// Instead, simply use the following to take advantage of
// variant-aware dependency resolution. You can learn more about
// the 'implementation' configuration in the section about
// new dependency configurations.
implementation project(':foo')

// You can, however, keep using variant-specific configurations when
// targeting external dependencies. The following line adds 'app-magic'
// as a dependency to only the 'debug' version of your module.

debugImplementation 'com.example.android:app-magic:12.3' 
}

Я изменил:

releaseCompile project(path: ':MyLib', configuration: 'appReleaseApp')
debugCompile project(path: ':MyLib', configuration: 'appDebug')

в

implementation project(':MyLib')

но у меня все еще есть эта ошибка: Error:Failed to resolve: Could not resolve project :MyLib.

lib gradle:

apply plugin: 'com.android.library'

android {
    publishNonDefault true
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
    }
    buildTypes {
        debug {
            ...
        }
        releaseApp {
            ...
        }
        releaseSdk {
            ...'
        }
    }
    flavorDimensions "default"

    productFlavors {
        flavor1{
            ...
        flavor2{
            ...
        }
        flavor3{
            ...
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
    compile 'com.google.android.gms:play-services-gcm:10.2.6'
    compile 'com.google.android.gms:play-services-location:10.2.6'
}

apply plugin: 'maven'

uploadArchives {
    repositories {
        mavenDeployer {
            repository(url: mavenLocal().url)
        }
    }
}

app gradle:

apply plugin: 'com.android.application'

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 12
        versionName "5.0.2"
    }

    buildTypes {
        release {
            ...
        }
        debug {
            ...
        }
    }
    flavorDimensions "default"

    productFlavors {
        flavor1 {
            ...
        }

        flavor2 {
            ...
        }
    }

    testOptions {
        unitTests {
            all {
                jvmArgs '-noverify'
                systemProperty 'robolectric.logging.enable', true
            }
        }
    }
}

repositories {
    flatDir {
        dirs 'libs'
    }
}
dependencies {
    //    releaseCompile project(path: ':MyLib', configuration: 'appRelease')
    //    debugCompile project(path: ':MyLib', configuration: 'appDebug')
    implementation project(':MyLib')

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.google.android.gms:play-services-maps:10.2.6'
    compile 'com.google.android.gms:play-services-location:10.2.6'
    compile 'com.google.android.gms:play-services-analytics:10.2.6'
    compile 'com.google.android.gms:play-services-gcm:10.2.6'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:gridlayout-v7:25.3.1'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.facebook.stetho:stetho:1.4.1'
    compile 'com.facebook.stetho:stetho-okhttp3:1.4.1'
    compile 'com.android.support:percent:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:2.1.0'
    testCompile 'org.robolectric:robolectric:3.1.4'
    testCompile 'org.assertj:assertj-core:1.7.1'

    compile 'com.flipboard:bottomsheet-core:1.5.0'
    compile 'com.flipboard:bottomsheet-commons:1.5.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
}

apply plugin: 'com.google.gms.google-services'

Пожалуйста, помогите

4b9b3361

Ответ 1

Google добавила дополнительную инструкцию, как ее решить: Устранить ошибки сборки, связанные с сопоставлением зависимостей

Причина ошибки сборки:

В вашем приложении есть тип сборки, в котором нет зависимости от библиотеки.

Например, ваше приложение включает в себя тип "промежуточной сборки", но зависимость включает в себя только тип сборки "debug" и "release".

Обратите внимание, что нет проблемы, когда зависимость библиотеки включает сборку типа, которого нет в вашем приложении. Это потому, что плагин просто никогда запросы, которые строят тип из зависимости.

Разрешение

Используйте matchFallbacks для указания альтернативных совпадений для заданного типа сборки, как показано ниже:

// In the app build.gradle file.
android {
    buildTypes {
        debug {}
        release {}
        staging {
            // Specifies a sorted list of fallback build types that the
            // plugin should try to use when a dependency does not include a
            // "staging" build type. You may specify as many fallbacks as you
            // like, and the plugin selects the first build type that's
            // available in the dependency.
            matchingFallbacks = ['debug', 'qa', 'release']
        }
    }
}

Ответ 2

После того, как вы столкнулись с той же проблемой, я, наконец, объявил точно такие же buildTypes как в файлах build.gradle для приложений, так и в модулях.

В вашем случае добавление

buildTypes {
    debug {}
    releaseApp {}
    releaseSdk {}
}

к вашему модулю build.gradle должен сделать трюк.

Обязательно измените любой "проект компиляции" на "проект реализации".

Надеюсь, что это поможет

Ответ 3

С новым плагином, разрешение зависимых от версии

implementation project(':MyLib')

должен иметь точные соответствия типов сборки. Руководство по миграции описывает это

Например, невозможно сделать вариант "отладки" вариант "выпуска" через этот механизм, поскольку производитель и потребитель не будет соответствовать. (В этом случае имя "debug" относится к опубликованный объект конфигурации, упомянутый выше в публикации Раздел зависимостей.) Теперь, когда мы публикуем две конфигурации, для компиляция и один для времени выполнения, этот старый способ выбора одного конфигурация действительно больше не работает.

Итак, старый метод

releaseCompile project(path: ':foo', configuration: 'debug')

больше не будет работать.

Пример

В вашем примере это будет выглядеть так:

В приложении build.gradle:

apply plugin: 'com.android.application'

android {
  buildTypes {
    debug {}
    releaseApp {}
    releaseSdk {}
  }
  ...
  dependencies {
    implementation project(':MyLib')
  }
}

В модуле /lib 'MyLib' build.gradle:

apply plugin: 'com.android.library'

android {
  buildTypes {
    debug {}
    releaseApp {}
    releaseSdk {}
  }
}

Поэтому тип сборки должен точно соответствовать, не более того.

Использование резервных копий типа сборки

Новая функция, называемая matchFallbacks, может использоваться для определения типов построения по умолчанию, если подмодуль не определяет тип сборки.

Используйте matchFallbacks для указания альтернативных совпадений для заданного типа сборки (...)

Например, если модуль /lib 'MyLib' gradle будет выглядеть так:

apply plugin: 'com.android.library'

android {
  buildTypes {
    debug {}
    releaseLib {}
  }
}

В приложении build.gradle можно указать следующее:

apply plugin: 'com.android.application'

android {
  buildTypes {
    debug {}
    releaseApp {
        ...
        matchingFallbacks = ['releaseLib']
    }
    releaseSdk {
        ...
        matchingFallbacks = ['releaseLib']
    }
  }
  ...
  dependencies {
    implementation project(':MyLib')
  }
}

Отсутствующие размеры вкуса

Использовать missingDimensionStrategy в блоке defaultConfig, чтобы указать по умолчанию, плагин должен выбирать из каждого отсутствующего размера

android {
    defaultConfig {
        missingDimensionStrategy 'minApi', 'minApi18', 'minApi23'
        ...
    }
}

Ответ 4

Сегодня у меня также была такая же проблема после перехода на Android Studio 3. Проблема заключается в том, что gradle не может разрешить определенные библиотеки из-за проблемы с сетью. Причины могут быть разными. Если вы работаете за прокси-сервером, вам нужно добавить параметры прокси-сервера в файл gradle.properties:

systemProp.http.proxyHost=<proxy_host>
systemProp.http.proxyPort=<proxy_port
systemProp.https.proxyHost=<proxy_host>
systemProp.https.proxyPort=<proxy_port>

В моем случае у меня была еще одна проблема. Моя компания использует самоподписанный SSL-сертификат, поэтому у SSL-соединения возникла проблема. Если это применимо и для вас, вы можете снова установить параметр в файле gradle.properties следующим образом:

org.gradle.jvmargs=-Djavax.net.ssl.trustStore="/usr/lib/jvm/java-8-oracle/jre/lib/security/cacerts" -Djavax.net.ssl.trustStoreType=JKS -Djavax.net.ssl.keyStorePassword=changeit

Чтобы быть более понятным, вы можете нажать ссылку "Показать детали" в журнале сообщений в Android Studio. Этот журнал будет более полезен, чтобы решить, какова реальная проблема.

Ответ 5

У меня была та же проблема, я нашел эту страницу миграции: Создать соответствующие типы соответствия

В нем указано:

Выберите значения по умолчанию для отсутствующих типов сборки
Если пользователь настраивает тип сборки, который нет у производителя, вам необходимо вручную сопоставить тип сборки потребителя с одним из производителя. Например, если ваш модуль приложения настраивает тип сборки и его зависимость от библиотечного модуля, "mylibrary", нет, плагин Android генерирует следующую ошибку сборки:

Error:Failed to resolve: Could not resolve project :mylibrary.
Required by: project :app

Чтобы устранить эту ошибку, вам нужно указать тип сборки из "mylibrary", который должен иметь плагин Android, соответствующий типу сборки "установка". Вы можете сделать это с помощью свойства buildTypeMatching в файле build.gradle приложения, как показано ниже:

// Add the following to the consumer build.gradle file.
android {
    ...
    // Tells the Android plugin to use a library 'debug' build type
    // when a 'staging' build type is not available. You can include
    // additional build types, and the plugin matches 'staging' to the
    // first build type it finds from the one you specify. That is,
    // if 'mylibrary' doesn't include a 'debug' build type either, the
    // plugin matches 'staging' with the producer 'release' build type.
    buildTypeMatching 'staging', 'debug', 'release'
}

Добавление buildTypeMatching исправило это для меня, не создавая ненужные типы в моей библиотеке