对于Dagger2,在初学者严重简直可以用三个字形容。因为这颠覆了你在未使用他之前的代码习惯。而在有些了解之后,发现这其实是一个很好的办法去复用一些方法,你不用因为一个方法中的若干参数而烦恼。
参考资料:http://blog.csdn.net/tiankong1206/article/details/45967935
MVP开发模式,现如今最流行的开发模式,将逻辑、显示、业务层分离,有助于项目升级以及维护。
Retrofit,一个能帮你处理复杂的网络访问。集成OKHttp,使用RxJava中观察者、订阅者模式执行操作。现在更新到了Retrofit2,如果你从来没了解过Retrofit,请参考
http://blog.csdn.net/liuhongwei123888/article/details/50375283
如果你从Retrofit转到Retrofit2,请参考
http://blog.csdn.net/xie666/article/details/50492912
好了,在了解完上述的一些知识点,我们现在要开始着手工作了。
1、环境搭建
在app下的build.gradle下参照下面的gradle配置
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' // 注释处理
apply plugin: 'me.tatarka.retrolambda'// lambda 表达式
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
applicationId "com.yetland.daggerdemo"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
// 注释冲突
packagingOptions {
exclude 'META-INF/services/javax.annotation.processing.Processor'
}
// 使用Java1.8
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0'
compile 'com.android.support:support-v4:23.1.0'
compile 'com.jakewharton:butterknife:7.0.1'
// dagger2 依赖部分
provided 'javax.annotation:jsr250-api:1.0'
compile 'com.google.dagger:dagger:2.0.2'
compile 'com.google.dagger:dagger-compiler:2.0.2'
// RxJava依赖部分
compile 'io.reactivex:rxandroid:1.1.0'
compile 'io.reactivex:rxjava:1.1.0'
compile 'com.jakewharton.rxbinding:rxbinding:0.3.0'
compile 'com.jakewharton.rxbinding:rxbinding-appcompat-v7:0.3.0'
compile 'com.jakewharton.rxbinding:rxbinding-design:0.3.0'
// Retrofit依赖部分
compile 'com.google.code.gson:gson:2.5' // gson
compile 'com.squareup.retrofit2:retrofit:2.0.1' // retrofit
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.picasso:picasso:2.5.2'
}
使用lambda表达式还需要在项目的build.gradle下配置
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
// 配置信息
classpath 'me.tatarka:gradle-retrolambda:3.2.5'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
基本的环境搭建在这步结束后就可以完成了。Dagger2依赖部分比较复杂,可以参考上述的博客进行操作。
2、怎么使用?
网上有很多教程都是关于GitHub上个人仓库信息的获取,在这里也对这实现进行简单的梳理。并拓展获取天气资讯的Demo。
2.1需求分析
我们在搭建好了环境变量之后,对需求进行一下分析:
- 在github提供的API下,对个人仓库以及个人信息进行获取
- 返回数据是标准的JSON格式,在这里提供一个JSON转换成Java实体类的便捷方式:Json数据转Java实体类
- 对返回的JSON数据转换成实体类
- 在RecycleView上进行显示
- 天气信息的获取并显示
2.2预先了解
问:
- 怎么从GitHub提供的API获取数据?
- GitHub提供的API返回数据长什么样的?
- RecycleView怎么使用?
答:
- https://api.github.com 是GitHub提供的API,在域名后加上/users/{user}/repos,{user}是指定的用户名,这样你就可以获取个人仓库的信息了。例如:https://api.github.com/users/SpikeKing/repos
- 当你点击了上个链接之后,显示的数据就是返回数据的样子。
- Recycleview的一些基本知识,请参考:RecycleView知识
3、开始上手
用MVP的开发模式,将项目分成model、presenter、view三个包。
3.1创建实体类
3.1.1UserModel
用户信息实体类
因为要涉及到点击个人信息跳转到指定仓库,需要在Activity间传递实体类,所以要序列化。
public class UserModel implements Serializable {
public String login;
public String avatar_url;
public String name;
public String repos_url;
// getter and setter 省略...
}
3.1.2 RepoModel
仓库信息实体类
public class RepoModel {
private String name;
private String description;
private String language;
}
3.2创建Dagger2
3.2.1怎么创建?
创建过程Module->Component->绑定
子Module需要依赖父Module
3.2.2Module
1.MainModule
@Module
public class MainModule {
private final AppApplication mApp;
public MainModule(AppApplication application) {
mApp = application;
}
@Provides
@Singleton
protected Application provideApplication() {
return mApp;
}
@Provides
@Singleton
protected Resources provideResources() {
return mApp.getResources();
}
}
对于每个Module,必须要有@Provide方法或者在构造函数前@Inject
2.ApiModule(提供GitHubService)
@Module
public class ApiModule {
@Provides
@Singleton
protected RestApi provideGitHubService() {
Retrofit retrofit = new Retrofit.Builder()
.client(new OkHttpClient())
.baseUrl(RestApi.ENDPOINT)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 添加Rx适配器
.addConverterFactory(GsonConverterFactory.create()) // 添加Gson转换器
.build();
return retrofit.create(RestApi.class);
}
}
public interface RestApi {
String ENDPOINT = "https://api.github.com";
// 获取库, 获取的是一组RepoModel数据
@GET("/users/{user}/repos")
Observable<ArrayList<RepoModel>> getRepoData(@Path("user") String user);
// 获取是单个UserModel
@GET("/users/{user}")
Observable<UserModel> getUserData(@Path("user") String user);
}
3.2.3Component
1.AppComponent
@Singleton
@Component(modules = {MainModule.class, ApiModule.class})
public interface AppComponent {
Application getApplication();
RestApi getService();
}
3.2.3AppApplication
public class AppApplication extends Application {
private AppComponent appComponent;
public static AppApplication get(Context context){
return (AppApplication) context.getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
// DaggerAPPComponent是在正确配置了Module和APPComponent之后,再BuildProject之后会自动生成。APPComponent依赖了多少个Module在Builder的时候就需要注入多少Module
appComponent = DaggerAppComponent.builder()
.apiModule(new ApiModule())
.mainModule(new MainModule(this))
.build();
}
public AppComponent getAppComponent() {
return appComponent;
}
}
写了Application之后,一定要记得在AndroidManifest.xml文件下添加android:name=”你的Application”否则会报错
成功之后的编译结果:会在apt下自动生成以Dagger开头+类名的类
3.3UserListActivity
3.3.1 BaseActivity
创建一个BaseActivity供继承,且实现依赖注入入口。
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActivityComponent(AppApplication.get(this).getAppComponent());
}
protected abstract void setupActivityComponent(AppComponent appComponent);
}