在Android项目中使用阿里云maven

阿里云云效maven地址

官方的gradle配置指南

在 build.gradle 文件中加入以下代码:

1
2
3
4
5
6
7
8
9
allprojects {
repositories {
maven {
url 'https://maven.aliyun.com/repository/public/'
}
mavenLocal()
mavenCentral()
}
}

如果想使用其它代理仓,以使用spring仓为例,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
allProjects {
repositories {
maven {
url 'https://maven.aliyun.com/repository/public/'
}
maven {
url 'https://maven.aliyun.com/repository/spring/'
}
mavenLocal()
mavenCentral()
}
}

加入你要引用的文件信息:

1
2
3
dependencies {
compile '[GROUP_ID]:[ARTIFACT_ID]:[VERSION]'
}

执行命令

1
gradle dependencies 或 ./gradlew dependencies 安装依赖

手动配置

两个build.gradle文件的区别

build.gradle(Project):用来配置整个工程的
build.gradle(app):用来配置app的

引入仓库

    根据官方配置说明,我们在工程build.gradle文件指定位置添加代码,然后sync Now

添加依赖

查找依赖包

    在阿里云maven仓库服务→文件搜索→gav模式,可以搜索我们想添加的依赖包,三个搜索框和引入依赖的代码呈对应关系

    以okhttp4.9.0为例,在搜索框中输入,com.squareup.okhttp3、okhttp、4.9.0,可以看到

按照格式写入

    按照官方给定的格式,在App的build.gradle文件的dependencies中加入

1
2
3
4
5
6
//  官方的格式
// compile '[GROUP_ID]:[ARTIFACT_ID]:[VERSION]'

dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
}

implementation与compile的区别

    至于我们为什么使用implementation而不是compile引入

  1. implementation: 对于使用了该命令编译的依赖,对该项目有依赖的项目将无法访问到使用该命令编译的依赖中的任何程序,也就是将该依赖隐藏在内部,而不对外部公开。
  2. api: 完全等同于compile指令。
  3. compile: 这种是我们最常用的方式,使用该方式依赖的库将会参与编译和打包。
  4. testCompile: 只在单元测试代码的编译以及最终打包测试apk时有效。
  5. debugCompile: 只在debug模式的编译和最终的debug apk打包时有效。
  6. releaseCompile: 仅仅针对Release模式的编译和最终的Release apk打包,比如我们使用的leakcanary。
使用添加的依赖

    编写几行代码测试一下okhttp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("https://www.baidu.com").build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {

}

@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
Log.d("TAG", "onResponse: " + response.body().string());
}
});

    添加网络权限

1
<uses-permission android:name="android.permission.INTERNET"/>

    看下log,成功

常用的第三方库

1
2
3
4
5
6
7
implementation 'com.squareup.okhttp3:okhttp:4.9.0'//okhttp
implementation 'com.github.bumptech.glide:glide:4.12.0'//glide库
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'//glide注解库
implementation 'com.google.code.gson:gson:2.8.4'//Gson
implementation 'com.youth.banner:banner:2.1.0'//banner
implementation 'androidx.recyclerview:recyclerview:1.2.1'//RecyclerView
implementation 'androidx.viewpager2:viewpager2:1.1.0-beta01'//ViewPager2