拦截器模版附带MVP防止内存泄漏

post请求路径不用加后面的参数,放入Map中就行,公共参数在拦截器中


拦截器:

public class MyInterCeptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        HttpUrl build = request.url().newBuilder().addQueryParameter("source", "android").build();

        Request build1 = request.newBuilder().url(build).build();

        return chain.proceed(build1);
    }
}


OKHttpUtils:

public class OKHttpUtils {
    Handler handler = new Handler();

    private static volatile OKHttpUtils okhttputils;

    public static OKHttpUtils getInstence(){
        if(null==okhttputils){
            synchronized (OKHttpUtils.class){
                if(okhttputils==null){
                    okhttputils = new OKHttpUtils();
                }
            }
        }
        return okhttputils;
    }
    public void post(String url, Map<String,String> map,final MView mview,final Class clas){
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new MyIntercapter())
                .build();
        FormBody.Builder builder = new FormBody.Builder();
        if(map!=null&&!map.isEmpty()){
            for(Map.Entry<String,String> entry:map.entrySet()){
                builder.add(entry.getKey(),entry.getValue());
            }
        }

        final Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mview.onShibai(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                final Object o = gson.fromJson(string, clas);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        mview.onChenggong(o);
                    }
                });
            }
        });
    }
}


防止内存泄漏:

V层//判断new的P层为不为空,为空调用P层的销毁方法

protected void onDestroy() {
        super.onDestroy();

        if (presenter != null) {
            presenter.detachView();
        }
    }

P层:

判断V层的接口为不为空,不为空变为空

public void detachView() {
        if (null != iv) {
            iv = null;
        }
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值