Android studio Gradle 7.0+ 版本的.aar引入方式说明

新建的Androidi项目编译错误, 莫名其妙的错误, 踩坑了, 记录一下,各位大神指正.

1. buildg.radle中引入 aar错误

android {
    repositories {
        flatDir {
            //引入libs目录下的aar
            dirs 'libs'
        }
    }
}

A problem occurred evaluating project ':Jnilib'.
> Build was configured to prefer settings repositories over project repositories but repository 'flatDir' was added by build file 'Jnilib/build.gradle'

说明

Android studio Gradle 7.0 之前的版本的配置和7.0+版本的不同, 其中 aar库文件的引入区别变化比较大, settings.gradle根配置中没有之前的,repositories了, 加上直接编译错误.

解决方法

settings.gradle :

pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()

        flatDir {
            //Gradle 7.0+ 版本的.aar引入方式:
            // DemoJni: 为工程根目录名称(府项目名称);
            // Jnilib: 子项目的目录名称
            dirs '../DemoJni/Jnilib'
        }
    }
}

rootProject.name = "DemoJni"
include ':app'
include ':Jnilib'

子模块中build.gradle配制方法

Jnilib: 子目录的guild.gradle中不能添加repositories

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])

     ..........................

    //Gradle 7.0+ 版本的.aar引入方式
    api(name: 'libs/HulkAidlLib-debug', ext: 'aar')
}

文件举例:

plugins {
    id 'com.android.library'
}

android {
    namespace 'com.hulk.udp.demo.socks.proxy'
    compileSdk 33

    defaultConfig {
        minSdk 24
        targetSdk 33

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        consumerProguardFiles "consumer-rules.pro"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
            version "3.22.1"
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    //Gradle 7.0+ 版本的.aar引入方式
    api(name: 'libs/HulkAidlLib-debug', ext: 'aar')
}

Sync 就正常了.

你可能感兴趣的:(android,studio,android,gradle)