1. 网络架构
在讲网络框架之前,咱们先来说说开发模式。智汀云盘应用的开发模式是 MVP(Model-View-Presenter)模式:
- Model 提供数据
- View 负责显示
- Controller/Presenter 负责逻辑的解决
MVP 是从 MVC 演变而来的,但它与 MVC 有着一个重大的区别:
- 在 MVP 中 View 并不间接应用 Model,它们是通过 Presenter(MVC 中的 Controller)来进行通信的,所有的交互都产生再 Presenter 内容
- 而 MVC 中 View 读取数据不是通过 Controller 而是间接从 Model 中读取。
MVP 有以下三个劣势:
- View 与 Model 齐全隔离;
- Presenter 与 View 的具体实现技术无关;
- 能够进行 View 的模仿测试。
接着咱们持续来看网络申请框架,智汀云盘应用的网络申请框架是:Retrofit + RxJava + OkHttp。
- Retrofit 是 Square 公司基于 OkHttp 封装的 Android 网络申请框架;
- OkHttp 是一个网络申请库,也是 Square 开源的;
- RxJava 在 GitHub 上的形容是:a library for composing asynchronous and event-based programs by using observable sequences(应用可察看序列编写异步和基于事件的程序的库),这使得咱们切换线程的操作变得更加简略。
Retrofit + RxJava + OkHttp 是当下 Android 用 Java 语言开发最风行的网络申请形式。
上面是网络框架集成的步骤:
1)导入相干的库
api rootProject.ext.dependencies["gson"]
api rootProject.ext.dependencies["okhttp"]
api rootProject.ext.dependencies["loggingInterceptor"]
api rootProject.ext.dependencies["retrofit"]
api rootProject.ext.dependencies["converterGson"]
api rootProject.ext.dependencies["rxjavaAdapter"]
api rootProject.ext.dependencies["rxandroid"]
api rootProject.ext.dependencies["rxjava"]
2)创立 Retrofit 实例 <
public class RetrofitManager {
...
private RetrofitManager(String baserUrl) {retrofit = new Retrofit.Builder()
.baseUrl(baserUrl)
.client(getOkHttpClient())
.addConverterFactory(GsonConverterFactory.create(GsonConverter.getGson()))
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build();}
...
}
3)增加 OkHttp 配置
public class RetrofitManager {
...
private OkHttpClient getOkHttpClient() {OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(getHttpLoginInterceptor())
.connectTimeout(HttpConfig.connectTimeout, TimeUnit.SECONDS)
.readTimeout(HttpConfig.readTimeOut, TimeUnit.SECONDS)
.writeTimeout(HttpConfig.writeTimeOut, TimeUnit.SECONDS)
.retryOnConnectionFailure(true);
return builder.build();}
...
}
4)创立一个接口
public interface ApiService {...}
注:ApiService 的办法必须是 Observable<BaseResponseEntity<T>> 类型
5)用 Retrofit 创立接口实例 ApiService
public class RetrofitManager {
...
public <T> T create(Class<T> service) {return retrofit.create(service);
}
...
}
6)配合 RxJava 应用并封装
public abstract class BasePresenter<M extends IModel, V extends IView> implements IPresenter<V> {
...
/**
* 网络申请
*
* @param observable
* @param callback
* @param <T>
*/
public <T> void executeObservable(Observable<BaseResponseEntity<T>> observable, RequestDataCallback<T> callback) {observable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BaseResponseEntity<T>>() {
@Override
public void onSubscribe(@NonNull Disposable d) {mModel.addDisposable(d);
if (mView != null && callback != null && callback.isLoading())
mView.showLoading();}
@Override
public void onNext(@NonNull BaseResponseEntity<T> response) {if (callback != null) {if (response.getStatus() == 0) { // 胜利
callback.onSuccess(response.getData());
} else { // 失败
if (mView != null) {if (callback != null && callback.isLoading())
mView.hideLoading();
if (response.getStatus() != ErrorConstant.INVALID_AUTH) // 如果不是有效的受权才须要土司提醒
showError(response.getReason()); // 提醒错误信息
mView.showError(response.getStatus(), response.getReason()); // 提醒错误信息
}
callback.onFailed(response.getStatus(), response.getReason());
}
}
}
@Override
public void onError(@NonNull Throwable e) {e.printStackTrace();
String error = "";
if (e instanceof ConnectException || e instanceof UnknownHostException) {error = "网络异样,请查看网络";} else if (e instanceof TimeoutException || e instanceof SocketTimeoutException) {error = "网络不畅,请稍后再试!";} else if (e instanceof JsonSyntaxException) {error = "数据解析异样";} else {error = "服务端谬误";}
if (mView != null) {if (callback != null && callback.isLoading())
mView.hideLoading();
showError(error);
}
}
@Override
public void onComplete() {if (mView != null && callback != null && callback.isLoading())
mView.hideLoading();}
});
}
...
}
附:
- Retrofit: GitHub – square/retrofit: A type-safe HTTP client for Android and the JVM
- RxJava:GitHub – ReactiveX/RxJava: RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.
- OkHttp:GitHub – square/okhttp: Square’s meticulous HTTP client for the JVM, Android, and GraalVM.