1、Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOCRetrofit2.0+RxJava+Dragger2实现不一样的Android网络架构搭建封装实现网络框架这种行为固然不错,但是这需要自身具备比较高的能力,而很多时候我们没有那样的能力把它封装的足够好。这时我们使用开源的网络框架也未尝不是一件好事,github上面知名的网络框架已经经过了很多app的验证,在一定意义上是非常符合我们在实际的项目开发所需要的。Android开发中几个知名的开源的网络框架有android-async-http,Volley,OkHttp等,国人 开发的xUtils快速开
2、发框架也比较流行。android-async-http是个很老牌的网络框架,非常的经典。Volley官方推荐的,自不必说。OkHttp可以说是后起之秀,现在非常流行,Android系统底层api都有用到,所以是非常niubility. 我们很多开发者大都在小型公司,不了解大公司是怎么做Android网络框架的,也想知道那些用户量过千万的APP到底用了些什么技术,下面有两张图片,让我们一起来了解一下Android版的美团和Uber到底用了些什么技术。 Uber看完你会发现其实这些用户量过亿的APP也使用了很多的开源框架,而且这些开源框架中大多数其实都是我们平常在开发中所常用到的,并不陌生。可能大
3、多数人对Retrofit,Rxjava这些还不太熟悉,那话不多说,今天我们就来讲讲怎么用Retrofit2.0+RxJava+Dragger2来实现Android网络构架搭建,给大家提供一种思路,供大家参考参考。RxJava是一种响应式编程框架,采用观察者设计模式。最核心的是Observables(被观察者,事件源)和Subscribers(观察者)这两个东西,RxAndroid是Rxjava在Android上的实现。Dragger2 - 是一种依赖注入框架,可以大大节省我们的代码量,便于维护。在这里我就不费过多笔墨来介绍着三个东西了,今天的主题是提供一种如何搭建一个不一样的网络框架的思路。如
4、果读者对这三个框架不是很了解的话,可以自行的Google脑补一下。 首先,就是开始把这些框架引入到咱们的项目中来作为依赖库,在app/build.gradle文件中添加 apply plugin: com.android.applicationapply plugin: com.neenbedankt.android-aptandroid compileSdkVersion 23 buildToolsVersion 23.0.2 defaultConfig applicationId com.finddreams.retrofit minSdkVersion 15 targetSdkVersi
5、on 23 versionCode 1 versionName 1.0buildTypes release minifyEnabled false proguardFiles getDefaultProguardFile(proguard-android.txt), proguard- rules.pro dependencies compile fileTree(include: *.jar, dir: libs)testCompile junit:junit:4.12compile com.android.support:appcompat-v7:23.1.1/retrofitcompil
6、e com.squareup.retrofit2:retrofit:2.0.0-beta4/gson解析compile com.squareup.retrofit2:converter-gson:2.0.0-beta4/rxjavacompile io.reactivex:rxandroid:1.1.0compile com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4/dragger2provided org.glassfish:javax.annotation:10.0-b28apt com.google.dagger:dagger-compi
7、ler:2.0.2compile com.google.dagger:dagger:2.0.2因为Dragger2是基于注解的,它会预先生成一些类文件,所以需要在整个项目的/build.gradle文件中加上apt工具: buildscript repositories jcenter() dependencies classpath com.android.tools.build:gradle:2.0.0-beta6 classpath com.neenbedankt.gradle.plugins:android-apt:1.8 / NOTE: Do not place your appli
8、cation dependencies here; they belong / in the individual module build.gradle files allprojects repositories jcenter() task clean(type: Delete) delete rootProject.buildDir接着开始写一个提供Retrofit的单例类: /* * Retrofit的实体类 */ public class RestApiAdapter private static Retrofit retrofit = null;public static Ret
9、rofit getInstance() if (retrofit = null) GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(); OkHttpClient okHttpClient = new OkHttpClient(); OkHttpClient.Builder builder = okHttpClient.newBuilder(); builder.retryOnConnectionFailure(true); retrofit = new Retrofit.Builder().clie
10、nt(okHttpClient) .baseUrl(ConstantApi.BaiduUrl) .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(RxJavaCallAdapterFactory.create() .build(); return retrofit;addCallAdapterFactory(RxJavaCallAdapterFactory.create() 这个方法就是RxJava和Retrofit结合的关键。接着我们为Retrofit 提供一个service接口,声明api接口地址和所需要的参
11、数,这里我们使用XXAPI提供的天气接口,实现根据城市名称查询天气的功能,接口地址: 代码如下: /* * 天气接口Api */public interface WeatherApiService /* * 查询天气 */ GET(apistore/weatherservice/cityname) Observable queryWeather(Header(apikey) String apikey, Query(cityname) String cityname);返回一个Observable被观察者/事件源的意思是交给RxJava来处理。 然后我们写一个BaseSubsribe观察者来管
12、理网络请求开始结束,成功与失败:public abstract class BaseSubsribe extends Subscriber private static final String TAG = BaseSubsribe;Overridepublic void onStart() super.onStart(); Log.i(TAG, onStart);Overridepublic void onNext(T t) Log.i(TAG, response + t.toString(); onSuccess(t);Overridepublic void onCompleted() L
13、og.i(TAG, onCompleted);public abstract void onSuccess(T result);Overridepublic void onError(Throwable e) e.printStackTrace(); Log.i(TAG, onError + e.getMessage();接着我们写一个WeatherInteractor接口连接service类:public interface WeatherInteractor Subscription queryWeather(String apikey, String cityname, BaseSubs
14、ribe subsribe);然后是这个接口的实现类: public class WeatherInteractorImpl implements WeatherInteractor private final WeatherApiService api; Inject public WeatherInteractorImpl(WeatherApiService myApi) this.api = myApi; Override public Subscription queryWeather(String apikey, String cityname, BaseSubsribe subsr
15、ibe) Observable observable = api.queryWeather(apikey, cityname); Subscription subscribe = observable.subscribeOn(Schedulers.io().observeOn(AndroidSchedulers.mainThread().subscribe(subsribe); return subscribe; 接下来是如何使用Dragger2的时候,知道Dragger2的都知道有几个概念,一个是Module:主要提供依赖对象比如context, rest api ; 一个是inject:注
16、解,用在需要依赖对象的地方;另一个是Componet:用来连接Module和inject 首先定义一个Module类,提供需要注入依赖的对象: Module类 Module public class InteractorModule Pvides public Retrofit provideRestAdapter() return RestApiAdapter.getInstance(); Providespublic WeatherApiService provideHomeApi(Retrofit restAdapter) return restAdapter.create(Weathe
17、rApiService.class);Provides public WeatherInteractor provideHomeInteractor(WeatherApiService myApi) return new WeatherInteractorImpl(myApi);接着是写一个Componet类:/* * 声明AppComponent组件 * * author finddreams * address */SingletonComponent(modules = InteractorModule.class,)public interface AppComponent void
18、inject(App app);WeatherInteractor getWeatherInteractor();然后我们在Application中初始化这个AppComponent:/* * Application类 * * author finddreams * address */public class App extends Application private AppComponent component;Overridepublic void onCreate() super.onCreate();setDraggerConfig();public AppComponent c
19、omponent() return component;public static App get(Context context) return (App) context.getApplicationContext();/* * 初始化Dragger,DaggerAppComponent是自动生成,需要Rebuild */private void setDraggerConfig() component = DaggerAppComponent.builder().interactorModule(new InteractorModule()ld();component.inject(th
20、is);这里需要注意的是,由于Dagger2是预编译生成一个类,所以我们需要Rebuild项目,才会生成DaggerAppComponent这个类。如果开发中出现import com.finddreams.retrofit.api.config.DaggerAppComponent; 找不到这个类的错误这时就需要重新的Rebuild项目 最后我们就可以在Activity中开始使用了: /* * 主页 * * author finddreams * address */ public class MainActivity extends AppCompatActivity private App
21、Component component; private WeatherInteractor weatherInteractor; private EditText city; private TextView queryresult; Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); city = (EditText) findViewById(R.id.city); qu
22、eryresult = (TextView) findViewById(R.id.queryresult); /获取到AppComponent组件 component = App.get(this).component(); /通过AppComponent拿到WeatherInteractor weatherInteractor = component.getWeatherInteractor(); findViewById(R.id.query).setOnClickListener(new View.OnClickListener() Oide public void onClick(Vi
23、ew v) queryWeatherData(); );public void queryWeatherData() String content = city.getText().toString();/调用查询天气接口的方法Subscription subscription = weatherInteractor.queryWeather(ConstantApi.baiduKey, content, new BaseSubsribe() Overridepublic void onSuccess(WeatherResultBean result) WeatherResultBean.RetDataEntity retData = result.getRetData();queryresult.setText(retData.getCity() + : + retData.getWeather() + : + retData.getDate();Overridepublic void onError(Throwable e) super.onError(e);queryresult.setText(查询失败););/取消请求/subscription.unsubscribe();我们看下项目运行的结果图:
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1