![Retrofit20+RxJava+Dragger2實(shí)現(xiàn)不一樣的Android網(wǎng)絡(luò)架構(gòu)搭建_第1頁(yè)](http://file3.renrendoc.com/fileroot_temp3/2021-12/16/c2c60b7e-1e88-4594-a18f-a238a81f777a/c2c60b7e-1e88-4594-a18f-a238a81f777a1.gif)
![Retrofit20+RxJava+Dragger2實(shí)現(xiàn)不一樣的Android網(wǎng)絡(luò)架構(gòu)搭建_第2頁(yè)](http://file3.renrendoc.com/fileroot_temp3/2021-12/16/c2c60b7e-1e88-4594-a18f-a238a81f777a/c2c60b7e-1e88-4594-a18f-a238a81f777a2.gif)
![Retrofit20+RxJava+Dragger2實(shí)現(xiàn)不一樣的Android網(wǎng)絡(luò)架構(gòu)搭建_第3頁(yè)](http://file3.renrendoc.com/fileroot_temp3/2021-12/16/c2c60b7e-1e88-4594-a18f-a238a81f777a/c2c60b7e-1e88-4594-a18f-a238a81f777a3.gif)
![Retrofit20+RxJava+Dragger2實(shí)現(xiàn)不一樣的Android網(wǎng)絡(luò)架構(gòu)搭建_第4頁(yè)](http://file3.renrendoc.com/fileroot_temp3/2021-12/16/c2c60b7e-1e88-4594-a18f-a238a81f777a/c2c60b7e-1e88-4594-a18f-a238a81f777a4.gif)
![Retrofit20+RxJava+Dragger2實(shí)現(xiàn)不一樣的Android網(wǎng)絡(luò)架構(gòu)搭建_第5頁(yè)](http://file3.renrendoc.com/fileroot_temp3/2021-12/16/c2c60b7e-1e88-4594-a18f-a238a81f777a/c2c60b7e-1e88-4594-a18f-a238a81f777a5.gif)
版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、Retrofit2.0+RxJava+Dragger2實(shí)現(xiàn)不一樣的Android網(wǎng)絡(luò)架構(gòu)搭建封裝實(shí)現(xiàn)網(wǎng)絡(luò)框架這種行為固然不錯(cuò),但是這需要自身具備比較高的能力,而很多時(shí)候我們沒(méi)有那樣的能力把它封裝的足夠好。這時(shí)我們使用開(kāi)源的網(wǎng)絡(luò)框架也未嘗不是一件好事,github上面知名的網(wǎng)絡(luò)框架已經(jīng)經(jīng)過(guò)了很多app的驗(yàn)證,在一定意義上是非常符合我們?cè)趯?shí)際的項(xiàng)目開(kāi)發(fā)所需要的。Android開(kāi)發(fā)中幾個(gè)知名的開(kāi)源的網(wǎng)絡(luò)框架有android-async-http,Volley,OkHttp等,國(guó)人 開(kāi)發(fā)的xUtils快速開(kāi)發(fā)框架也比較流行。android-async-http是個(gè)很老牌的網(wǎng)絡(luò)框架,非常的經(jīng)典。Voll
2、ey官方推薦的,自不必說(shuō)。OkHttp可以說(shuō)是后起之秀,現(xiàn)在非常流行,Android系統(tǒng)底層api都有用到,所以是非常niubility. 我們很多開(kāi)發(fā)者大都在小型公司,不了解大公司是怎么做Android網(wǎng)絡(luò)框架的,也想知道那些用戶(hù)量過(guò)千萬(wàn)的APP到底用了些什么技術(shù),下面有兩張圖片,讓我們一起來(lái)了解一下Android版的美團(tuán)和Uber到底用了些什么技術(shù)。 Uber看完你會(huì)發(fā)現(xiàn)其實(shí)這些用戶(hù)量過(guò)億的APP也使用了很多的開(kāi)源框架,而且這些開(kāi)源框架中大多數(shù)其實(shí)都是我們平常在開(kāi)發(fā)中所常用到的,并不陌生??赡艽蠖鄶?shù)人對(duì)Retrofit,Rxjava這些還不太熟悉,那話(huà)不多說(shuō),今天我們就來(lái)講講怎么用Retr
3、ofit2.0+RxJava+Dragger2來(lái)實(shí)現(xiàn)Android網(wǎng)絡(luò)構(gòu)架搭建,給大家提供一種思路,供大家參考參考。RxJava是一種響應(yīng)式編程框架,采用觀(guān)察者設(shè)計(jì)模式。最核心的是Observables(被觀(guān)察者,事件源)和Subscribers(觀(guān)察者)這兩個(gè)東西,RxAndroid是Rxjava在A(yíng)ndroid上的實(shí)現(xiàn)。Dragger2 - 是一種依賴(lài)注入框架,可以大大節(jié)省我們的代碼量,便于維護(hù)。在這里我就不費(fèi)過(guò)多筆墨來(lái)介紹著三個(gè)東西了,今天的主題是提供一種如何搭建一個(gè)不一樣的網(wǎng)絡(luò)框架的思路。如果讀者對(duì)這三個(gè)框架不是很了解的話(huà),可以自行的Google腦補(bǔ)一下。 首先,就是開(kāi)始把這些框架引入
4、到咱們的項(xiàng)目中來(lái)作為依賴(lài)庫(kù),在app/build.gradle文件中添加 apply plugin: 'com.android.application'apply plugin: 'com.neenbedankt.android-apt'android compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig applicationId "com.finddreams.retrofit" minSdkVersion 15 targetSdkVersion 2
5、3 versionCode 1 versionName "1.0"buildTypes release minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard- ' dependencies compile fileTree(include: '*.jar', dir: 'libs')testCompile 'junit:junit:4.12'comp
6、ile 'com.android.support:appcompat-v7:23.1.1'/retrofitcompile '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.0'compile 'com.squareup.retrofit2:adapter-rxjava
7、:2.0.0-beta4'/dragger2provided 'org.glassfish:javax.annotation:10.0-b28'apt 'com.google.dagger:dagger-compiler:2.0.2'compile 'com.google.dagger:dagger:2.0.2'因?yàn)镈ragger2是基于注解的,它會(huì)預(yù)先生成一些類(lèi)文件,所以需要在整個(gè)項(xiàng)目的/build.gradle文件中加上apt工具: buildscript repositories jcenter() dependencies cla
8、sspath 'com.android.tools.build:gradle:2.0.0-beta6' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' / NOTE: Do not place your application dependencies here; they belong / in the individual module build.gradle files allprojects repositories jcenter() task clean(type: Delete
9、) delete rootProject.buildDir接著開(kāi)始寫(xiě)一個(gè)提供Retrofit的單例類(lèi): /* * Retrofit的實(shí)體類(lèi) */ public class RestApiAdapter private static Retrofit retrofit = null;public static Retrofit getInstance() if (retrofit = null) GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(); OkHttpClient okHttpClient
10、= new OkHttpClient(); OkHttpClient.Builder builder = okHttpClient.newBuilder(); builder.retryOnConnectionFailure(true); retrofit = new Retrofit.Builder().client(okHttpClient) .baseUrl(ConstantApi.BaiduUrl) .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(RxJavaCallAdapterFactory.cre
11、ate() .build(); return retrofit;addCallAdapterFactory(RxJavaCallAdapterFactory.create() 這個(gè)方法就是RxJava和Retrofit結(jié)合的關(guān)鍵。接著我們?yōu)镽etrofit 提供一個(gè)service接口,聲明api接口地址和所需要的參數(shù),這里我們使用百度API提供的天氣接口,實(shí)現(xiàn)根據(jù)城市名稱(chēng)查詢(xún)天氣的功能,接口地址: 代碼如下: /* * 天氣接口A(yíng)pi */public interface WeatherApiService /* * 查詢(xún)天氣 */ GET("apistore/weatherserv
12、ice/cityname") Observable<WeatherResultBean> queryWeather(Header("apikey") String apikey, Query("cityname") String cityname);返回一個(gè)Observable被觀(guān)察者/事件源的意思是交給RxJava來(lái)處理。 然后我們寫(xiě)一個(gè)BaseSubsribe觀(guān)察者來(lái)管理網(wǎng)絡(luò)請(qǐng)求開(kāi)始結(jié)束,成功與失?。簆ublic abstract class BaseSubsribe<T> extends Subscriber<
13、;T> 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() Log.i(TAG, "onCompleted&
14、quot;);public abstract void onSuccess(T result);Overridepublic void onError(Throwable e) e.printStackTrace(); Log.i(TAG, "onError" + e.getMessage();接著我們寫(xiě)一個(gè)WeatherInteractor接口連接service類(lèi):public interface WeatherInteractor Subscription queryWeather(String apikey, String cityname, BaseSubsribe
15、<WeatherResultBean> subsribe);然后是這個(gè)接口的實(shí)現(xiàn)類(lèi): public class WeatherInteractorImpl implements WeatherInteractor private final WeatherApiService api; Inject public WeatherInteractorImpl(WeatherApiService myApi) this.api = myApi; Override public Subscription queryWeather(String apikey, String citynam
16、e, BaseSubsribe<WeatherResultBean> subsribe) Observable<WeatherResultBean> observable = api.queryWeather(apikey, cityname); Subscription subscribe = observable.subscribeOn(Schedulers.io().observeOn(AndroidSchedulers.mainThread().subscribe(subsribe); return subscribe; 接下來(lái)是如何使用Dragger2的時(shí)候,
17、知道Dragger2的都知道有幾個(gè)概念,一個(gè)是Module:主要提供依賴(lài)對(duì)象比如context, rest api ; 一個(gè)是inject:注解,用在需要依賴(lài)對(duì)象的地方;另一個(gè)是Componet:用來(lái)連接Module和inject 首先定義一個(gè)Module類(lèi),提供需要注入依賴(lài)的對(duì)象: Module類(lèi) Module public class InteractorModule Pvides public Retrofit provideRestAdapter() return RestApiAdapter.getInstance(); Providespublic WeatherApiServic
18、e provideHomeApi(Retrofit restAdapter) return restAdapter.create(WeatherApiService.class);Provides public WeatherInteractor provideHomeInteractor(WeatherApiService myApi) return new WeatherInteractorImpl(myApi);接著是寫(xiě)一個(gè)Componet類(lèi):/* * 聲明AppComponent組件 * * author finddreams * address */SingletonComponen
19、t(modules = InteractorModule.class,)public interface AppComponent void inject(App app);WeatherInteractor getWeatherInteractor();然后我們?cè)贏(yíng)pplication中初始化這個(gè)AppComponent:/* * Application類(lèi) * * author finddreams * address */public class App extends Application private AppComponent component;Overridepublic vo
20、id onCreate() super.onCreate();setDraggerConfig();public AppComponent component() return component;public static App get(Context context) return (App) context.getApplicationContext();/* * 初始化Dragger,DaggerAppComponent是自動(dòng)生成,需要Rebuild */private void setDraggerConfig() component = DaggerAppComponent.bu
21、ilder().interactorModule(new InteractorModule()ld();component.inject(this);這里需要注意的是,由于Dagger2是預(yù)編譯生成一個(gè)類(lèi),所以我們需要Rebuild項(xiàng)目,才會(huì)生成DaggerAppComponent這個(gè)類(lèi)。如果開(kāi)發(fā)中出現(xiàn)import com.finddreams.retrofit.api.config.DaggerAppComponent; 找不到這個(gè)類(lèi)的錯(cuò)誤這時(shí)就需要重新的Rebuild項(xiàng)目 最后我們就可以在A(yíng)ctivity中開(kāi)始使用了: /* * 主頁(yè) * * author finddreams * add
22、ress */ public class MainActivity extends AppCompatActivity private AppComponent 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); queryresult = (TextView) findViewById(R.id.queryresult); /獲取到AppComponent組件 component = App.get(this).component(); /通過(guò)AppComponent拿到WeatherInteractor weatherInteracto
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度市政道路鋼筋施工分包合同
- 便利店?duì)I業(yè)員個(gè)人工作總結(jié)2024(9篇)
- 2025年電影產(chǎn)業(yè)收益分配策略協(xié)議
- 2025年臨時(shí)建筑項(xiàng)目施工合同樣本
- 2025年鑄幣及貴金屬制實(shí)驗(yàn)室用品項(xiàng)目申請(qǐng)報(bào)告模板
- 2025年聚苯硫醚(PPS)及合金項(xiàng)目規(guī)劃申請(qǐng)報(bào)告
- 2025年升級(jí)版?zhèn)€人代表授權(quán)合同
- 2025年小區(qū)護(hù)衛(wèi)服務(wù)合同范本
- 2025年醫(yī)療機(jī)構(gòu)衛(wèi)生用品清潔服務(wù)協(xié)議
- 2025年公民投票統(tǒng)一授權(quán)協(xié)議
- 八年級(jí)道德與法治下冊(cè)研課標(biāo)、說(shuō)教材-陳俊茹課件
- 建筑施工安全風(fēng)險(xiǎn)辨識(shí)分級(jí)管控指南
- 政務(wù)信息工作先進(jìn)單位事跡材料
- 《觸不可及》影視鑒賞課件
- 冀教版五年級(jí)英語(yǔ)下冊(cè)教學(xué)計(jì)劃(精選17篇)
- 外科感染教案
- 《一頁(yè)紙項(xiàng)目管理》中文模板
- 密度計(jì)法顆粒分析試驗(yàn)記錄(自動(dòng)和計(jì)算)
- 英語(yǔ)演講-機(jī)器人發(fā)展
- JJF(紡織)064-2013織物防鉆絨性試驗(yàn)儀(摩擦法)校準(zhǔn)規(guī)范
- JJF 1905-2021磁通計(jì)校準(zhǔn)規(guī)范
評(píng)論
0/150
提交評(píng)論