MVP框架——Android

高增
2023-12-01

个人用起来最舒服的MVP框架

框架使用

关于项目代码中的基础框架搭建
presenter和view的基类中加入了内存的优化
map介绍:
契约:连接M,V,P三层(通过接口实现的方式)
Model:数据的获取(一般是网络请求)
Presenter:代码逻辑的处理
View:控件等的展示

1.设置好你的Apiservice

Apiservice是你一切的基础,如果你需要使用网络请求的话`.

public interface IApi {
    //登陆注册
    @POST
    Observable<ResponseBody> postMap(@Url String url, @QueryMap Map<String, String> map);
    //GET复用
    @GET
    Observable<ResponseBody> getMap(@Url String url, @QueryMap Map<String, String> map);
    //delete复用
    @DELETE
    Observable<ResponseBody> deleteMap(@Url String url, @QueryMap Map<String, String> map);
    //文件上传
    @Multipart
    @POST
    Observable<ResponseBody> filePost(@Url String url, @Query("content") String content, @Part List<MultipartBody.Part> list);
    //put请求复用
    @PUT
    Observable<ResponseBody> putMap(@Url String url, @QueryMap Map<String, String> map);
}

2.设计好你的契约

第二步,设置好你的契约,用来连接三个层

public interface Contract {

    interface IView<T>{
        void OnSuccess(T t);
        void OnError(String error);
    }

//连接p层
    interface IPresenter{
        //发送复用
        void postMap(String url, Map<String, String> map, Class aClass);
        //获取复用
        void getMap(String url, Map<String, String> map, Class aClass);
        //删除复用
        void deleteMap(String url, Map<String, String> map, Class aClass);
        //多图上传
        void filePost(String url,String content, List<MultipartBody.Part>list, Class aClass);
        //put上传复用
        void putMap(String url, Map<String, String> map, Class aClass);
    }
//连接model
    interface IModel{
        //发送复用
        void postMap(String url, Map<String, String> map, Class aClass, ModelCallBack callBack);
        //获取复用
        void getMap(String url, Map<String, String> map, Class aClass, ModelCallBack callBack);
        //删除复用
        void deleteMap(String url, Map<String, String> map, Class aClass, ModelCallBack callBack);
        //多图上传
        void filePost(String url,String content, List<MultipartBody.Part>list, Class aClass,ModelCallBack callBack);
        //put上传复用
        void putMap(String url, Map<String, String> map, Class aClass,ModelCallBack callBack);
    }

    interface ModelCallBack<T>{
        void OnSuccess(T t);
        void OnError(String error);
    }

}

3.构建好网络工具类(2/3)

public class MyHttpUtils {

    //retrofit对象
    private final Retrofit mretrofit;
    private IApi miapi;

    //单例模式(双重锁)
    private static MyHttpUtils MY_HTTP_UTILS;
    public static MyHttpUtils getInstance(){
        if(MY_HTTP_UTILS == null){
            synchronized (MyHttpUtils.class){
                if(MY_HTTP_UTILS == null){
                    MY_HTTP_UTILS = new MyHttpUtils();
                }
            }
        }
        return MY_HTTP_UTILS;
    }

    //初始化ok
    public MyHttpUtils(){
        //拦截器
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        //设置
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //ok
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5,TimeUnit.SECONDS)
                .readTimeout(5,TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .addInterceptor(new HeaderInterceptor())
                .build();
        //retrofit
        mretrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        //结合
        miapi = mretrofit.create(IApi.class);
    }

    //接口
    public interface NetCallBack<T>{
        void onSuccess(T t);
        void onError(String error);
    }

    //网络判断
    public static boolean isNetWork(Context context){
        //系统
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //网络
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo!=null){
            return networkInfo.isAvailable();
        }
        return false;
    }

    //头参
    class HeaderInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //sp存储
            SharedPreferences user = MyApplication.context.getSharedPreferences("user", Context.MODE_PRIVATE);
            //取两个参数
            String userId = user.getString("userId","");
            String sessionId = user.getString("sessionId","");
//            Log.i("头参",userId+"分割"+sessionId);
            //创建请求
            Request build = chain.request();
            Request request = build.newBuilder()
                    .addHeader("userId",userId)
                    .addHeader("sessionId",sessionId)
                    .addHeader("ak","0110010010000")
                    .build();
            return chain.proceed(request);
        }
    }
    //

    //登陆注册等复用
    public void PostMap(String url, Map<String,String>map, final Class aClass, final NetCallBack netCallBack){
        miapi.postMap(url,map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {}

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            Object o = gson.fromJson(responseBody.string(),aClass);
                            if(netCallBack != null){
                                netCallBack.onSuccess(o);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(netCallBack != null){
                            netCallBack.onError(e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {}
                });
    }
    //get请求复用
    public void getMap(String url, Map<String,String>map, final Class aClass, final NetCallBack netCallBack){
        miapi.getMap(url, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Gson gson = new Gson();
                        try {
                            String obj = responseBody.string();
                            Object o = gson.fromJson(obj, aClass);
                            Log.i("信息",obj);
                            if (netCallBack!=null){
                                netCallBack.onSuccess(o);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (netCallBack!=null){
                            netCallBack.onError(e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

4.IModel

model和p层中通过实现契约中对应的接口做到mvp的逻辑分层

public class IModel implements Contract.IModel {
    @Override
    public void postMap(String url, Map<String, String> map, Class aClass, final Contract.ModelCallBack callBack) {
        MyHttpUtils.getInstance().PostMap(url, map, aClass, new MyHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Object o) {
                callBack.OnSuccess(o);
            }

            @Override
            public void onError(String error) {
                callBack.OnError(error);
            }
        });
    }

    @Override
    public void getMap(String url, Map<String, String> map, Class aClass, final Contract.ModelCallBack callBack) {
        MyHttpUtils.getInstance().getMap(url, map, aClass, new MyHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Object o) {
                callBack.OnSuccess(o);
            }

            @Override
            public void onError(String error) {
                callBack.OnError(error);
            }
        });
    }

    @Override
    public void deleteMap(String url, Map<String, String> map, Class aClass, final Contract.ModelCallBack callBack) {
        MyHttpUtils.getInstance().deleteMap(url, map, aClass, new MyHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Object o) {
                callBack.OnSuccess(o);
            }

            @Override
            public void onError(String error) {
                callBack.OnError(error);
            }
        });
    }

    @Override
    public void filePost(String url,String content, List<MultipartBody.Part> list, Class aClass, Contract.ModelCallBack callBack) {
        MyHttpUtils.getInstance().filePost(url, content, list, aClass, new MyHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Object o) {
                callBack.OnSuccess(o);
            }

            @Override
            public void onError(String error) {
                callBack.OnError(error);
            }
        });
    }

    @Override
    public void putMap(String url, Map<String, String> map, Class aClass, Contract.ModelCallBack callBack) {
        MyHttpUtils.getInstance().putMap(url, map, aClass, new MyHttpUtils.NetCallBack() {
            @Override
            public void onSuccess(Object o) {
                callBack.OnSuccess(o);
            }

            @Override
            public void onError(String error) {
                callBack.OnError(error);
            }
        });
    }
}

5.basepresenter和presenterImpl

public abstract class BasePresenter<V extends Contract.IView> implements Contract.IPresenter {

    //
    private IModel iModel;
    //弱引用
    private WeakReference<V> vWeakReference;

    //构造
    public BasePresenter(){
        iModel = new IModel();
    }

    //绑定
    public void attachView(V v){
        if(vWeakReference == null){
            vWeakReference = new WeakReference<>(v);
        }
    }

    //解绑
    public void detachView(){
        if(vWeakReference != null){
            vWeakReference.clear();
            vWeakReference = null;
        }
    }

    //get
    public V getView(){
        return vWeakReference.get();
    }
    public IModel getiModel(){
        return iModel;
    }

}
public class PresenterImpl extends BasePresenter {
    @Override
    public void postMap(String url, Map<String, String> map, Class aClass) {
        getiModel().postMap(url, map, aClass, new Contract.ModelCallBack() {
            @Override
            public void OnSuccess(Object o) {
                getView().OnSuccess(o);
            }

            @Override
            public void OnError(String error) {
                getView().OnError(error);
            }
        });
    }

    @Override
    public void getMap(String url, Map<String, String> map, Class aClass) {
        getiModel().getMap(url, map, aClass, new Contract.ModelCallBack() {
            @Override
            public void OnSuccess(Object o) {
                getView().OnSuccess(o);
            }

            @Override
            public void OnError(String error) {
                getView().OnError(error);
            }
        });
    }

    @Override
    public void deleteMap(String url, Map<String, String> map, Class aClass) {
        getiModel().deleteMap(url, map, aClass, new Contract.ModelCallBack() {
            @Override
            public void OnSuccess(Object o) {
                getView().OnSuccess(o);
            }

            @Override
            public void OnError(String error) {
                getView().OnError(error);
            }
        });
    }

    @Override
    public void filePost(String url,String content, List<MultipartBody.Part> list, Class aClass) {
        getiModel().filePost(url, content, list, aClass, new Contract.ModelCallBack() {
            @Override
            public void OnSuccess(Object o) {
                getView().OnSuccess(o);
            }

            @Override
            public void OnError(String error) {
                getView().OnError(error);
            }
        });
    }

    @Override
    public void putMap(String url, Map<String, String> map, Class aClass) {
        getiModel().putMap(url, map, aClass, new Contract.ModelCallBack() {
            @Override
            public void OnSuccess(Object o) {
                getView().OnSuccess(o);
            }

            @Override
            public void OnError(String error) {
                getView().OnError(error);
            }
        });
    }
}

6.view层基类及实类调用

实类继承基类重写抽象方法即可(fragment等基类方式相同)
实类中通过基类暴露出来的p对象调用网络方法即可实现网络请求
调用逻辑:
p调用到p层中的对应方法——p层中方法通过契约的桥梁调用到model中的对应方法,进行网络请求。
返回的数据按照与之相反的逻辑传递到实类view中的OnSuccess方法中
eg:p.getMap(Constant.InformationShowList_URL,map, Bean_Recommend.class);

public abstract class BaseActivity<P extends PresenterImpl> extends AppCompatActivity implements Contract.IView {

    //泛型对象
    public P p;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        init();
    }

    void init(){
        if(getLayout() != 0){
            setContentView(getLayout());
            if(p == null){
                p = initPresenter();
                p.attachView(this);
            }
            initView();
        }else {
            //参数不合法异常
            throw new IllegalArgumentException();
        }
    }

    //初始化
    protected abstract P initPresenter();
    protected abstract int getLayout();
    protected abstract void initView();
//    protected abstract void initData();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(p != null){
            p.detachView();
            p = null;
        }
    }

}

总结

到这里就ok了,接下来就可以调用方法进行网络请求了

 类似资料: