




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
1、Retrofit2.0+RxJava+Dragger2實現(xiàn)不一樣的Android網(wǎng)絡(luò)架構(gòu)搭建封裝實現(xiàn)網(wǎng)絡(luò)框架這種行為固然不錯,但是這需要自身具備比較高的能力,而很多時候我們沒有那樣的能力把它封裝的足夠好。這時我們使用開源的網(wǎng)絡(luò)框架也未嘗不是一件好事,github上面知名的網(wǎng)絡(luò)框架已經(jīng)經(jīng)過了很多app的驗證,在一定意義上是非常符合我們在實際的項目開發(fā)所需要的。Android開發(fā)中幾個知名的開源的網(wǎng)絡(luò)框架有android-async-http,Volley,OkHttp等,國人 開發(fā)的xUtils快速開發(fā)框架也比較流行。android-async-http是個很老牌的網(wǎng)絡(luò)框架,非常的經(jīng)典。Voll
2、ey官方推薦的,自不必說。OkHttp可以說是后起之秀,現(xiàn)在非常流行,Android系統(tǒng)底層api都有用到,所以是非常niubility. 我們很多開發(fā)者大都在小型公司,不了解大公司是怎么做Android網(wǎng)絡(luò)框架的,也想知道那些用戶量過千萬的APP到底用了些什么技術(shù),下面有兩張圖片,讓我們一起來了解一下Android版的美團(tuán)和Uber到底用了些什么技術(shù)。 Uber看完你會發(fā)現(xiàn)其實這些用戶量過億的APP也使用了很多的開源框架,而且這些開源框架中大多數(shù)其實都是我們平常在開發(fā)中所常用到的,并不陌生。可能大多數(shù)人對Retrofit,Rxjava這些還不太熟悉,那話不多說,今天我們就來講講怎么用Retr
3、ofit2.0+RxJava+Dragger2來實現(xiàn)Android網(wǎng)絡(luò)構(gòu)架搭建,給大家提供一種思路,供大家參考參考。RxJava是一種響應(yīng)式編程框架,采用觀察者設(shè)計模式。最核心的是Observables(被觀察者,事件源)和Subscribers(觀察者)這兩個東西,RxAndroid是Rxjava在Android上的實現(xiàn)。Dragger2 - 是一種依賴注入框架,可以大大節(jié)省我們的代碼量,便于維護(hù)。在這里我就不費過多筆墨來介紹著三個東西了,今天的主題是提供一種如何搭建一個不一樣的網(wǎng)絡(luò)框架的思路。如果讀者對這三個框架不是很了解的話,可以自行的Google腦補一下。 首先,就是開始把這些框架引入
4、到咱們的項目中來作為依賴庫,在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'因為Dragger2是基于注解的,它會預(yù)先生成一些類文件,所以需要在整個項目的/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接著開始寫一個提供Retrofit的單例類: /* * Retrofit的實體類 */ 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() 這個方法就是RxJava和Retrofit結(jié)合的關(guān)鍵。接著我們?yōu)镽etrofit 提供一個service接口,聲明api接口地址和所需要的參數(shù),這里我們使用百度API提供的天氣接口,實現(xiàn)根據(jù)城市名稱查詢天氣的功能,接口地址: 代碼如下: /* * 天氣接口Api */public interface WeatherApiService /* * 查詢天氣 */ GET("apistore/weatherserv
12、ice/cityname") Observable<WeatherResultBean> queryWeather(Header("apikey") String apikey, Query("cityname") String cityname);返回一個Observable被觀察者/事件源的意思是交給RxJava來處理。 然后我們寫一個BaseSubsribe觀察者來管理網(wǎng)絡(luò)請求開始結(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();接著我們寫一個WeatherInteractor接口連接service類:public interface WeatherInteractor Subscription queryWeather(String apikey, String cityname, BaseSubsribe
15、<WeatherResultBean> subsribe);然后是這個接口的實現(xiàn)類: 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; 接下來是如何使用Dragger2的時候,
17、知道Dragger2的都知道有幾個概念,一個是Module:主要提供依賴對象比如context, rest api ; 一個是inject:注解,用在需要依賴對象的地方;另一個是Componet:用來連接Module和inject 首先定義一個Module類,提供需要注入依賴的對象: Module類 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);接著是寫一個Componet類:/* * 聲明AppComponent組件 * * author finddreams * address */SingletonComponen
19、t(modules = InteractorModule.class,)public interface AppComponent void inject(App app);WeatherInteractor getWeatherInteractor();然后我們在Application中初始化這個AppComponent:/* * Application類 * * 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是自動生成,需要Rebuild */private void setDraggerConfig() component = DaggerAppComponent.bu
21、ilder().interactorModule(new InteractorModule()ld();component.inject(this);這里需要注意的是,由于Dagger2是預(yù)編譯生成一個類,所以我們需要Rebuild項目,才會生成DaggerAppComponent這個類。如果開發(fā)中出現(xiàn)import com.finddreams.retrofit.api.config.DaggerAppComponent; 找不到這個類的錯誤這時就需要重新的Rebuild項目 最后我們就可以在Activity中開始使用了: /* * 主頁 * * 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(); /通過AppComponent拿到WeatherInteractor weatherInteracto
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 北京汽車托運合同范本
- 2025年泰州貨運從業(yè)資格證怎么考
- 修復(fù)車交易合同范本
- 醫(yī)院弱電集成合同范本
- 制衣廠勞動合同范本
- 主廚合同范本
- 與中介定金合同范本
- 棉花勞務(wù)合同范本
- 冠名使用合同范本
- 勞動合同范本完整
- 客源國概況-韓國課件
- 道路建筑材料電子教案(全)
- 《一頁紙項目管理》中文模板
- 《淡水養(yǎng)殖基礎(chǔ)知識》
- 英語演講-機器人發(fā)展
- 《尹定邦設(shè)計學(xué)概論》試題及答案
- 黃河流域生態(tài)保護(hù)和高質(zhì)量發(fā)展知識競賽試題及答案(共52題)
- 1、1~36號元素電子排布式、排布圖
- advantrol-pro v2.70學(xué)習(xí)版系統(tǒng)組態(tài)使用手冊
- 職業(yè)院校技能大賽沙盤模擬企業(yè)經(jīng)營賽項規(guī)程
- 國網(wǎng)新聞宣傳與企業(yè)文化管理專責(zé)題庫匯總-下(判斷、簡答題)
評論
0/150
提交評論