Simple的MVP封装

来源:互联网 发布:ubuntu 16.04装软件 编辑:程序博客网 时间:2024/06/05 18:55

基于OKHTTP,OKHTTP-utils洪洋的库,https认证,带有token
学习MVP架构还是建议,去学习:dagger2(类似于spring框架)
,butterknife ,Rxjava ,逻辑看起来更加简洁,解耦,学习简单的MVP之后建议去学习这三个库,才能感受到他们的魅力

public abstract class BaseInteractor {
protected Gson mGson;
protected OkHttpUtils okHttpUtils;
protected final AppApplication app;
protected final String token;

public BaseInteractor(){    mGson = new Gson();    app = AppApplication.getAppInstance();    token = app.getToken();    okHttpUtils =app.getInitOkHttpUtils();}public void cancelTag(int tag){    okHttpUtils.cancelTag(tag);}public static  class  Build{    public String mToken;    public Build token(String mToken){        this.mToken  = mToken;        return this;    }    public BaseInteractor build() {        return new BaseInteractor() {};    }}

}

登陆的例子:

public class LoginInteractorImpl extends BaseInteractor implements LoginInteractor {

String jsonBean ;private ReLoginBean bean;private RequestCall call;@Overridepublic void login(final Object tClazz, final Class<T> tBean, final onLoginRepListener rep, final OnLoginFinishedListener listener) {     jsonBean = mGson.toJson(tClazz);    call = okHttpUtils.postString()            .url(URLValue.LoginUrl)            //          .addHeader("Token" ,token)   登陆获取token            .content(jsonBean)            .mediaType(MediaType.parse("application/json; charset=utf-8"))            .build();    call.execute(new Callback<ReLoginBean>() {         @Override         public boolean validateReponse(Response response, int id) {                    int code = response.code();                    CodeHolder holder = new CodeHolder(code);                   if (response.code() != 200){                       listener.onFailure(holder.getMessage());                   }                       return super.validateReponse(response, id);                }        @Override        public ReLoginBean parseNetworkResponse(Response response, int id) throws Exception {            String reLoginBean = response.body().string();            ReLoginBean bean = (ReLoginBean) GsonUtil.changeGsonToBean(reLoginBean, tBean);            return bean;        }        @Override        public void onError(Call call, Exception e, int id) {}        @Override        public void onResponse(ReLoginBean response, int id) {                app.setToken(response.getToken());                listener.onSuccessEntity(response);        }    });}public void cancel(){    call.cancel();}

}
//具体的处理登陆的业务层

public interface LoginInteractor {

 interface onLoginRepListener{     void onNotNet(String msg);     void onPreStart();     void onPreHttp();     void onUsernameError();     void onPasswordError(); }

登陆模块的接口
interface OnLoginFinishedListener {

    void onRequestPWError();    void onSuccess(String tData);    void onSuccessEntity(ReLoginBean t);    void onFailure(String error);    void onFinsh();}//需要给两个对象 如果服务器接收的是json,not params ,request Bean , response beanvoid login(Object object ,Class<T> tClass , onLoginRepListener rep , OnLoginFinishedListener listener);

}

//回调给UI界面的(activity)
public class LoginPresenterImpl implements ILoginPresenter, LoginInteractor.OnLoginFinishedListener, LoginInteractor.onLoginRepListener {

private ILoginView view;private LoginInteractor interactor ;public LoginPresenterImpl(ILoginView view) {    this.view = view;    interactor = new LoginInteractorImpl<T>();}@Overridepublic void onLogin(String uName, String pwd ) {    //之后对这些 数据加密   // interactor.login(uName , pwd , this , this);}@Overridepublic void onUsernameError() {    view.onToast("用户名输入错误");}@Overridepublic void onPasswordError() {    view.onToast("密码最低为6位数");}@Overridepublic void onNotNet(String msg) {    view.onToast("当前网络断开");}//网络处理的结果数据 密码错误的回调@Overridepublic void onRequestPWError() {    view.onToast("用户名或密码不正确");}//网络处理的结果数据@Overridepublic void onSuccess(String tData) {}@Overridepublic void onSuccessEntity(ReLoginBean t) {}//@Overridepublic void onFailure(String error) {    view.onToast("登陆失败" +error);}@Overridepublic void onFinsh() {    view.hideDialog();}@Overridepublic void onPreStart() {    view.showDialog();}@Overridepublic void onPreHttp() {}

}

在application初始化 okhttpUtils ,
sslParams = HttpsUtils.getSslSocketFactory(inputStreams, null, null);
initCache();
okHttpClient = new OkHttpClient.Builder()
// .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.addInterceptor(cacheInterceptor)
.addNetworkInterceptor(cacheInterceptor)
.retryOnConnectionFailure(true)
.cache(cache)
.build();
this.okHttpUtils = OkHttpUtils.initClient(okHttpClient);

//cache
private void initCache() {
if (cacheFile == null){
cacheFile = new File(Constants.getCacheDir());
}
if (cache == null){
cache = new Cache(cacheFile, 1024 * 1024 * 50);
}
if (cacheInterceptor == null)
cacheInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetworkUtils.isNetworkConnected()) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
}
Response response = chain.proceed(request);
if (NetworkUtils.isNetworkConnected()) {
int maxAge = 0;
// 有网络时, 不缓存, 最大保存时长为0
response.newBuilder()
.header(“Cache-Control”, “public, max-age=” + maxAge)
.removeHeader(“Pragma”)
.build();
} else {
// 无网络时,设置超时为14天
int maxStale = 60 * 60 * 24 * 14;
response.newBuilder()
.header(“Cache-Control”, “public, only-if-cached, max-stale=” + maxStale)
.removeHeader(“Pragma”)
.build();
}
return response;
}
};
}

0 0
原创粉丝点击