二:IView + IPresenter + 响应体泛型 + p

2020-08-05  本文已影响0人  我家猫猫不睡觉
public interface IView {
    /**
     * 显示错误消息
     *
     * @param message 内容
     */
    void showError(String message);

    /**
     * 显示加载进度
     */
    void showLoading();

    /**
     * 隐藏加载进度
     */
    void hideLoading();
}
/**
 *  presenter 持有view,可能会造成内存泄露,所以需要的onDestroy()加一个销毁view 的方法
 *  也需要考虑到,view被销毁
 *
 * @param <V> view
 */
public interface IPresenter<V extends IView> {

    void attach(V v);

    void dettach();
}
/**
 * 响应体
 *
 * @param <T> 泛型bean
 */
public class Response<T> {
    private String code; // 返回的code
    private T data; // 具体的数据结果
    private String msg; // message 可用来返回接口的说明

    public String getCode() {
        return code;
    }

    public void setCode(String ret) {
        this.code = ret;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public boolean isSuccess() {
        return "success".equalsIgnoreCase(code);
    }
}
/**
 *  考虑到内存泄漏问题,presenter 持有 view 的引用改为弱引用
 *
 * @param <V> view
 */

public abstract class AbstractPresenter<V extends IView> {

  private V mView;
    protected Context mContext;
    protected SoftReference<V> vSoftReference;

    public AbstractPresenter(Context context) {
        this.mContext = context;
        getCompositeDisposable();
    }

    // 解决 rxjava 请求内存泄漏问题
    private CompositeDisposable mCompositeDisposable;

    protected void bindView(V v) {
        if (vSoftReference == null) {
            vSoftReference = new SoftReference<>(v);
        }

        getCompositeDisposable();

        mView = (V) Proxy.newProxyInstance(v.getClass().getClassLoader(), getView().getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                if (vSoftReference == null || vSoftReference.get() == null) {
                    return null;
                }
                return method.invoke(vSoftReference.get(), objects);
            }
        });
    }

 public CompositeDisposable getCompositeDisposable() {
        if (mContext instanceof BaseActivity) {
            mCompositeDisposable = ((BaseActivity)mContext).getCompositeDisposable();
        } else if (mContext instanceof BaseMvpActivity) {
            mCompositeDisposable = ((BaseMvpActivity)mContext).getCompositeDisposable();
        } else {
            if (mCompositeDisposable == null) {
                mCompositeDisposable = new CompositeDisposable();
            }
        }
        return mCompositeDisposable;
    }

    protected V getView() {
        if (vSoftReference != null) {
            mView = vSoftReference.get();
        }
        return mView;
    }

    protected void destroy() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
        if (vSoftReference != null) {
            vSoftReference.clear();
            vSoftReference = null;
        }
    }

}
public abstract class ResponseException implements Consumer<Throwable> {

     /**
     * 未知错误
     */
    public static final int UNKNOWN = 1000;

    /**
     * 解析错误
     */
    public static final int PARSE_ERROR = 1001;

    /**
     * 网络错误
     */
    public static final int NETWORK_ERROR = 1002;

    /**
     * 协议错误
     */
    public static final int HTTP_ERROR = 1003;

    private Context mContext;

    public ResponseException(Context context) {
        if (context != null) {
            this.mContext = context.getApplicationContext();
        }
    }

    @Override
    public void accept(Throwable throwable) throws Exception {
        ApiException ex = handleException(throwable);
        if (BuildConfig.DEBUG) {
            Log.e("response--", throwable.toString());
        }
        onError(ex);
    }
    
    private ApiException handleException(Throwable e) {
    
        ApiException ex;
        if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            //解析错误
            ex = new ApiException(PARSE_ERROR, e.getMessage(), "解析错误!");
            return ex;
        } else if (e instanceof ConnectException) {
            //网络错误
            ex = new ApiException(NETWORK_ERROR, e.getMessage(), "网络错误!");
            return ex;
        } else if (e instanceof UnknownHostException) {
            //连接错误
            ex = new ApiException(NETWORK_ERROR, e.getMessage(), "网络错误!");
            return ex;
        }else if (e instanceof SocketTimeoutException) {
            //连接错误
            ex = new ApiException(NETWORK_ERROR, e.getMessage(), "网络连接超时!");
            return ex;
        } else if (e instanceof HttpException
                || e instanceof HttpRetryException
                || e instanceof retrofit2.adapter.rxjava2.HttpException) {
            ex = new ApiException(NETWORK_ERROR, e.getMessage(), "网络或服务器异常!");
            return ex;
        } else {
            //未知错误
            ex = new ApiException(UNKNOWN, e.getMessage(), "错误!");
            if (mContext != null) {
                if (!isNetworkReachable(mContext)) {
                    ex = new ApiException(NETWORK_ERROR, e.getMessage(), "网络未连接!");
                } else {
                    if (isNetworkAvailable(mContext)) {
                        ex = new ApiException(NETWORK_ERROR, e.getMessage(), "网络连接不可用!");
                    }
                }
            }
            return ex;
        }
    }
    
    public abstract void onError(ApiException e);

    /**
     * 网络是否连接
     *
     * @param context
     * @return
     */
    private boolean isNetworkReachable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            // 网络连接
            return true;
        }
        return false;
    }
    /**
     * 网络状态
     *
     * @param context
     * @return
     */
    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
        } else {
            //如果仅仅是用来判断网络连接
            //则可以使用 cm.getActiveNetworkInfo().isAvailable();
            @SuppressLint("MissingPermission") NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

ApiException

public class ApiException extends Exception {

    private int code;
    private String errMessage;
    private String showMessage;

    public ApiException(int code, String errMessage, String showMessage) {
        this.code = code;
        this.errMessage = errMessage;
        this.showMessage = showMessage;
    }
    
    public String getShowMessage() {
        return showMessage;
    }

    public void setShowMessage(String showMessage) {
        this.showMessage = showMessage;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getErrMessage() {
        return errMessage;
    }

    public void setErrMessage(String errMessage) {
        this.errMessage = errMessage;
    }
}

Android Retrofit2.0使用详解
https://blog.csdn.net/qq_35229022/article/details/93849660

RxJava入门
https://www.jianshu.com/p/a406b94f3188

上一篇下一篇

猜你喜欢

热点阅读