Talking about retrofit2.1+okhttp3 building MVP framework

This is the first blog. If there is anything wrong, please point out. I will learn with humility and make progress together. Thank you!


text:


The whole frame is shown in the following figure:



This is my own understanding of the MVP architecture, and I will briefly explain it for each file.


1. Explanation of each document

1. Adapters: The adapters for each View are stored in it;

2, base: some base classes are stored in it;


3. controllers: It stores various business network request control classes;

Note: Because when requesting background data, the background is unified by the Controller layer to accept the parameters, and then implement the business logic. So I use this to store various business network request classes.


4. daos: It stores the method classes and shared method classes of the operation database;

5, db: put the database initialization class in it;

6. entities: store some bean classes, message notification classes, network request classes, data callback classes, and retrofit asynchronous callback accepting classes;


7. http: It stores the network request class;


8. Interfaces: It stores some adapter callback interface classes, view layer callback interface classes, presenters layer callback interface classes, and retrofit unified api address service interface;


9. mineview: store some custom view, layout and other classes in it;

10. presenterimpls: It stores the concrete implementation classes of each business presenter;


11. service: It stores some service classes involved in the business;


12. utils: some common methods are stored in it;


13. Constants: some public parameters are stored in it;

public final static String ImageUrlIp = "x'x'x'x'x";


14. MyAapplication: It stores some global variables and Fresco initialization;

@Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
    }

The above is the framework I built for the MVP. If there is anything wrong, please point it out, thank you!


二、简单加载图片的具体实现


1、MainAtivity

1)、 MainActivity继承基类和BannerViewInter接口,并实现具体方法;

2)、实例化BannerPresenterInterImpl实现类,传入相关参数,调用图片请求显示方法;

3)、通过BannerViewInter接口的showBannerImg方法,接受返回图片地址url,调用图片显示方法,显示图片。

public class MainActivity extends BaseActivity implements BannerViewInter{

    @InjectView(R.id.am_sdv) public SimpleDraweeView bannerImg;


    private BannerPresenterInterImpl bannerPresenterInterimpl;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        super.init();
    }

    @Override
    public void initView() {
        bannerPresenterInterimpl = new BannerPresenterInterImpl(this,this);
        bannerPresenterInterimpl.getBannerImg();
    }

    @Override
    public void initEvent() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void showBannerImg(String url) {
        bannerImg.setImageURI(CommonUtils.setImgUri(url));
    }

    @Override
    public void onResponseFail(String fail) {
        Toast.makeText(this,fail,Toast.LENGTH_LONG).show();
    }

    @Override
    public void onFailure(String failure) {
        Toast.makeText(this,failure,Toast.LENGTH_LONG).show();
    }

2、BannerViewInter

1)、继承基类接口,自定义具体业务方法;

public interface BannerViewInter extends BaseViewInter{

    void showBannerImg(String url);

}
2)、基类接口。

public interface BaseViewInter {

    void onResponseFail(String fail);

    void onFailure(String failure);

}
3、BannerPresenterInterImpl

1)、继承BannerPresenterInter接口,实现具体方法;

2)、实例化BannerController控制类;

3)、调用图片请求方法;

4)、通过onBannerResponse方法 接收网络返回的数据;

5)、并调用BannerViewInter接口显示图片方法,回调给主线程,显示图片。

注:这里就可以实现具体的业务逻辑,通过接口,回调给主线程。

public class BannerPresenterInterImpl implements BannerPresenterInter {

    private Context context;
    private BannerViewInter bannerViewInter;
    private BannerController bannerController;

    public BannerPresenterInterImpl(Context context,BannerViewInter bannerViewInter){
        this.context = context;
        this.bannerViewInter = bannerViewInter;
    }



    public void getBannerImg(){
        bannerController = new BannerController(context,this);
        bannerController.getBanner();
    }


    @Override
    public void onBannerResponse(List<BannerResponse> responseList) {
        bannerViewInter.showBannerImg(responseList.get(0).getBannerUrl());
    }

    @Override
    public void onResponseFail(String fail) {
        bannerViewInter.onResponseFail(fail);
    }

    @Override
    public void onFailure(String failure) {
        bannerViewInter.onFailure(failure);
    }


}

4、BannerController

1)、初始化api服务接口、BannerPresenterInter接口等;

2)、调用服务接口显示图片的api,然后异步方法获取图片资源。

public class BannerController {

    private Context context;
    private BannerPresenterInter bannerPresenterInter;
    private ApiServiceInterface apiServiceInterface;

    public BannerController(Context context,BannerPresenterInter bannerPresenterInter){
        this.context = context;
        this.bannerPresenterInter = bannerPresenterInter;
        apiServiceInterface = RetrofitHttp.getApi();
    }

    public void getBanner(){
        Call<BannerObject> call = apiServiceInterface.homeBannerApi();

        call.enqueue(new Callback<BannerObject>() {
            @Override
            public void onResponse(Call<BannerObject> call, Response<BannerObject> response) {
                BannerObject object = response.body();
                if(object.getCode() == BaseController.CODE){
                    bannerPresenterInter.onBannerResponse(object.getResult());
                }else{
                    bannerPresenterInter.onResponseFail(object.getMessage());
                }
            }

            @Override
            public void onFailure(Call<BannerObject> call, Throwable t) {
                bannerPresenterInter.onFailure(t.toString());
            }
        });
    }



}
5、Okhttp

对Okhttp进行封装,添加打印日志等方法,方便查看返回结果及后台报错原因。

public class OkhttpHttp {


    public static OkHttpClient getOkHttpClient(){

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.i("message",message);
            }
        });
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        Log.i("request",request.toString());
                        Response proceed = chain.proceed(request);
                        Log.i("procceed",proceed.toString());
                        return proceed;
                    }
                })
                .addInterceptor(httpLoggingInterceptor)
                .connectTimeout(5000, TimeUnit.SECONDS)
                .build();

        return client;

    }


}

6、RetrofitHttp

添加请求返回可以接受的参数及api服务接口。

public class RetrofitHttp {

    public final static String IP = "xxxx";
    public final static String Http = "http://"+IP+"/mobile-web/mobile/";
    public static ApiServiceInterface apiServiceInterface;
    public static Retrofit retrofit;


    private RetrofitHttp(){}

    public static ApiServiceInterface getApi(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(Http)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(OkhttpHttp.getOkHttpClient())
                    .build();
        }
        apiServiceInterface = retrofit.create(ApiServiceInterface.class);

        return apiServiceInterface;
    }

}
7、ApiServiceInterface

里面存放统一api请求地址。

public interface ApiServiceInterface {

    String HOME = "home/"; //主页

    @GET(HOME+"getTopBannerList")
    Call<BannerObject> homeBannerApi(); //banner


}
8、BannerObject

里面存放请求回来,接受参数。

public class BannerObject extends BaseResponseObject{

    private List<BannerResponse> result;


    public List<BannerResponse> getResult() {
        return result;
    }

    public void setResult(List<BannerResponse> result) {
        this.result = result;
    }

}





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325988384&siteId=291194637