前言
本系列共三篇:
Android MVP入門(mén)到進(jìn)階之-簡(jiǎn)單入門(mén)
Android MVP入門(mén)到進(jìn)階之-結(jié)合Dagger2
Android MVP入門(mén)到進(jìn)階之- 系統(tǒng)框架集成(完結(jié))
通過(guò)前兩篇文章萎馅,整理了 MVP的簡(jiǎn)單框架的搭建 和 MVP結(jié)合Dagger2 的使用的例子,如果你還不熟悉MVP的使用請(qǐng)先查看前兩篇文章:
Android MVP入門(mén)到進(jìn)階之-簡(jiǎn)單入門(mén)
Android MVP入門(mén)到進(jìn)階之-結(jié)合Dagger2
這篇文章我們我們主要介紹窘疮,MVP 配合網(wǎng)絡(luò)框架Retrofit 的使用呵哨,因?yàn)槲覀傾PP開(kāi)發(fā)璃饱,網(wǎng)絡(luò)請(qǐng)求是很重要的一環(huán),當(dāng)然你也可以選擇自己喜歡的網(wǎng)絡(luò)框架進(jìn)行封裝馏臭。這里我們只講解 Retrofit2 基于 Dagger2的封裝和在MVP框架中的使用挺庞。
如果你還不知道什么事Retrofit是什么谁尸,你可能還需要補(bǔ)充一下知識(shí)
你真的會(huì)用Retrofit2嗎?Retrofit2完全教程
正式開(kāi)始
通過(guò)Android MVP入門(mén)到進(jìn)階之-結(jié)合Dagger2的封裝之后舅踪,我們的主體框架已經(jīng)定型,所以我們只需要添加一個(gè)HttpMoudle
就可以了,我們一步一步來(lái)添加
1. 在build.gradle中添加相關(guān)依賴(lài)
/*gson 用于解析json數(shù)據(jù)*/
implementation 'com.google.code.gson:gson:2.8.2'
/*retrofit 網(wǎng)絡(luò)請(qǐng)求框架 + rxjava */
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
/*添加Gson適配器*/
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.0.0'
/*okhttp日志打印*/
implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
/*rxjava*/
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.8'
2. 在A(yíng)ndroidManifest.xml 中添加網(wǎng)絡(luò)權(quán)限
<!-- 用于訪(fǎng)問(wèn)網(wǎng)絡(luò)症汹,網(wǎng)絡(luò)定位需要上網(wǎng) -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
添加BaseApiService接口 用于管理網(wǎng)絡(luò)請(qǐng)求接口和提供網(wǎng)絡(luò)請(qǐng)求的方法
/**
* @desc BaseApiService 為Retrofit框架提供接口請(qǐng)求注解,也是我們的網(wǎng)絡(luò)接口管理類(lèi)
* @author Marlon
* @date 2018/12/18
*/
public interface BaseApiService {
String BASE_URL_ZHIHU = " http://news-at.zhihu.com/";
@GET("/api/4/version/android/2.3.0")
Observable<BaseResponse<Resond>> getVerisionRxjava();
}
書(shū)寫(xiě)HttpMoudel
/**
* @desc HttpModule
* @author Marlon
* @date 2017/12/18
*/
@Module
public class HttpModule {
private static final String TAG = "HttpModule";
private static final long TIMEOUT = 1000;
@Singleton
@Provides
//構(gòu)建 Retrofit.Builder
Retrofit.Builder provideRetrofitBuilder() {
return new Retrofit.Builder();
}
@Singleton
@Provides
// 構(gòu)建 OkHttpClient.Builder
OkHttpClient.Builder provideOkHttpBuilder() {
return new OkHttpClient.Builder();
}
@Singleton
@Provides
//構(gòu)建 OkHttpClient 這里的攔截器 根據(jù)需求添加 需要才添加
OkHttpClient provideClient(OkHttpClient.Builder builder) {
CookieManger cookieJar =
new CookieManger(App.getInstance());
//儲(chǔ)存目錄
File mFile = new File(App.getInstance().getCacheDir() + "http");
// 10 MB 最大緩存數(shù)
long maxSize = 10 * 1024 * 1024;
Cache mCache = new Cache(mFile, maxSize);
Map<String, String> headers = new HashMap<>();
return builder
//添加Cookie管理硫朦,不需要管理可以不加贷腕,token在Cookie中的時(shí)候需要添加
.cookieJar(cookieJar)
//添加統(tǒng)一的請(qǐng)求頭
.addInterceptor(new BaseInterceptor(headers))
//添加base改變攔截器
.addInterceptor(new BaseUrlInterceptor())
//添加緩存攔截器
.addNetworkInterceptor(new CaheInterceptor(App.getInstance()))
//打印請(qǐng)求信息(可以自定義打印的級(jí)別1痴颉!)
.addNetworkInterceptor(new HttpLoggingInterceptor(message -> Log.e(TAG, message)).setLevel(HttpLoggingInterceptor.Level.BODY))
//相關(guān)請(qǐng)求時(shí)間設(shè)置
//鏈接時(shí)間
.connectTimeout(TIMEOUT, TimeUnit.SECONDS)
//讀取時(shí)間
.readTimeout(TIMEOUT, TimeUnit.SECONDS)
//寫(xiě)入時(shí)間
.writeTimeout(TIMEOUT, TimeUnit.SECONDS)
//添加緩存
.cache(mCache)
// 這里你可以根據(jù)自己的機(jī)型設(shè)置同時(shí)連接的個(gè)數(shù)和時(shí)間泽裳,我這里8個(gè)瞒斩,和每個(gè)保持時(shí)間為15s
.connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
.build();
}
@Singleton
@Provides
//構(gòu)建 Retrofit
Retrofit provideMyRetrofit(Retrofit.Builder builder, OkHttpClient client) {
return createRetrofit(builder, client, BaseApiService.BASE_URL_ZHIHU);
}
@Singleton
@Provides
//通過(guò) 反射機(jī)制 創(chuàng)建BaseApiService 這里BaseApiService 是封裝請(qǐng)求方法的接口類(lèi)
BaseApiService provideMyService(Retrofit retrofit) {
return retrofit.create(BaseApiService.class);
}
/**
* 通過(guò)Retrofit.Builder OkHttpClient url 構(gòu)建Retrofit
* @param builder
* @param client
* @param url
* @return
*/
private Retrofit createRetrofit(Retrofit.Builder builder, OkHttpClient client, String url) {
return builder.baseUrl(url)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
}
上面構(gòu)建OkHttpClient 的方法中涉及到很多的攔截器,詳細(xì)內(nèi)容請(qǐng)查看源碼demo涮总。
在 AppComponent中添加一下內(nèi)容胸囱,將HttpModule 添加到注解中
/**
* @desc AppComponent
* @author Marlon
* @date 2018/12/18
*/
@Singleton
@Component(modules = {AppModule.class, HttpModule.class})
public interface AppComponent {
App getContext(); // 提供App的Context
BaseApiService retrofitHelper(); //提供http的幫助類(lèi)
}
在A(yíng)PP中加入HttpModule 關(guān)聯(lián)
/**
* @desc App
* @author Marlon
* @date 2018/12/18
*/
public class App extends Application {
private static App instance;
public static AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static synchronized App getInstance() {
return instance;
}
public static AppComponent getAppComponent() {
if (appComponent == null) {
appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(instance))
.httpModule(new HttpModule())//這里添加
.build();
}
return appComponent;
}
public static void exitApp() {
try {
ActivityCollector.removeAllActivity();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
}
書(shū)寫(xiě) RxPresenter 類(lèi)使用
/**
* @desc RxPresenter 基于Rx的Presenter封裝,控制訂閱的生命周期
* @author Marlon
* @date 2018/12/18
*/
public class RxPresenter<T extends BaseView> implements BasePresenter<T> {
protected BaseApiService apiService;
protected Context mContext;
protected T mView;
private CompositeDisposable mCompositeDisposable;
public RxPresenter(App mContext, BaseApiService apiService) {
this.apiService = apiService;
this.mContext = mContext;
}
/**
* 取消注冊(cè) 中斷請(qǐng)求
*/
protected void unSubscribe() {
if (mCompositeDisposable != null) {
mCompositeDisposable.dispose();
mCompositeDisposable.clear();
}
}
//注冊(cè)
protected void addSubscribe(Disposable subscription) {
if (mCompositeDisposable == null) {
mCompositeDisposable = new CompositeDisposable();
}
mCompositeDisposable.add(subscription);
}
protected void addSubscribe(Observable<?> observable, BaseObserver observer) {
if (mCompositeDisposable == null) {
mCompositeDisposable = new CompositeDisposable();
}
mCompositeDisposable.add(observable.compose(RxHelper.io_main(mContext)).subscribeWith(observer));
}
@Override
public void attachView(T view) {
this.mView = view;
}
@Override
public void detachView() {
this.mView = null;
unSubscribe();
}
}
MainPresenter 繼承 RxPresenter
/**
* @desc MainPresenter
* @author Marlon
* @date 2018/12/18
*/
public class MainPresenter extends RxPresenter<MainContract.View> implements MainContract.Presenter {
@Inject
public MainPresenter(App app, BaseApiService service) {
super(app, service);
}
@Override
public void getVersion() {
//使用方式一
addSubscribe(apiService.getVerisionRxjava()
.compose(RxHelper.io_main(mContext))
.subscribeWith(new BaseObserver<Resond>() {
@Override
protected void onSuccess(Resond value) {
mView.showData(value.toString());
}
@Override
protected void onFailure(String message) {
mView.showData(message);
}
}));
//使用方式二
addSubscribe(apiService.getVerisionRxjava(), new BaseObserver<Resond>() {
@Override
protected void onSuccess(Resond value) {
}
@Override
protected void onFailure(String message) {
}
});
}
}
總結(jié)
到這里 我們框架就完全封裝完成,可能你看到這里還很迷瀑梗,確實(shí)我剛開(kāi)始學(xué)的時(shí)候也很迷烹笔,所以你需要把
RxJava 2、Retrofit2抛丽、Dagger2 ,慢慢搞懂谤职,然后照著demo寫(xiě)一遍,理解一下亿鲜,應(yīng)該還是不難允蜈,感覺(jué)用文字?jǐn)⑹鰧?shí)在是不好寫(xiě),如果有疑問(wèn)蒿柳,也可以留言哈饶套,我明白的可以答疑。
本文源碼地址demo,如果對(duì)你有幫助垒探,希望點(diǎn)一下小星星哈妓蛮!
到此,我們MVP框架系列已經(jīng)完結(jié)了圾叼。蛤克。。后面可能回再寫(xiě)一篇結(jié)合組件化的博客褐奥,以后再說(shuō)吧咖耘。
本文章為原創(chuàng)博客,轉(zhuǎn)載請(qǐng)注明出處撬码!