Welcome

首页 / 移动开发 / Android / AndroidStudio Gradle更换阿⾥云镜像的⽅法

AndroidStudio Gradle更换阿⾥云镜像的⽅法使⽤ Android Studio 开发时经常遇到编译卡住的问题,原因是 Gradle 下载依赖资源过慢。没办法,有长城在,还是得换镜像。同样,这是个普遍存在的问题,我们希望可以对它进⾏全局配置。在 .gradle (路径参考 C:\Users\username\.gradle )⽬录下新增 init.gradle ⽂件,内容如下:


allprojects{

  repositories {

    def ALIYUN_REPOSITORY_URL = 'http://maven.aliyun.com/nexus/content/groups/public'

    def ALIYUN_JCENTER_URL = 'http://maven.aliyun.com/nexus/content/repositories/jcenter'

    all { ArtifactRepository repo ->

      if(repo instanceof MavenArtifactRepository){

        def url = repo.url.toString()

        if (url.startsWith('https://repo1.maven.org/maven2') || url.startsWith('http://repo1.maven.org/maven2')) {

          project.logger.lifecycle "Repository ${repo.url} replaced by $ALIYUN_REPOSITORY_URL."

          remove repo

        }

        if (url.startsWith('https://jcenter.bintray.com/') || url.startsWith('http://jcenter.bintray.com/')) {

          project.logger.lifecycle "Repository ${repo.url} replaced by $ALIYUN_JCENTER_URL."

          remove repo

        }

      }

    }

    maven {

      url ALIYUN_REPOSITORY_URL

      url ALIYUN_JCENTER_URL

    }

  }

  buildscript{

    repositories {

      def ALIYUN_REPOSITORY_URL = 'http://maven.aliyun.com/nexus/content/groups/public'

      def ALIYUN_JCENTER_URL = 'http://maven.aliyun.com/nexus/content/repositories/jcenter'

      all { ArtifactRepository repo ->

        if(repo instanceof MavenArtifactRepository){

          def url = repo.url.toString()

          if (url.startsWith('https://repo1.maven.org/maven2') || url.startsWith('http://repo1.maven.org/maven2')) {

            project.logger.lifecycle "Repository ${repo.url} replaced by $ALIYUN_REPOSITORY_URL."

            remove repo

          }

          if (url.startsWith('https://jcenter.bintray.com/') || url.startsWith('http://jcenter.bintray.com/')) {

            project.logger.lifecycle "Repository ${repo.url} replaced by $ALIYUN_JCENTER_URL."

            remove repo

          }

        }

      }

      maven {

        url ALIYUN_REPOSITORY_URL

        url ALIYUN_JCENTER_URL

      }

    }

  }

}

如只需对单个项⽬进⾏配置,可以在项⽬根⽬录下的

 build.gradle 

⽂件中添加如下代码:

maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }

maven { url 'http://maven.aliyun.com/nexus/content/repositories/jcenter' }

maven { url 'http://maven.aliyun.com/nexus/content/repositories/google' }

maven { url 'http://maven.aliyun.com/nexus/content/repositories/gradle-plugin' }

搞定,下载速度飞起

如果上述的maven地址提示无法解析,则需要将maven中涉及的http改成https即可。