Android MVP框架

Android MVP框架_第1张图片

首先先看一下我的分包

interfaces:

        API接口地址;

        网络请求框架;

mvp:

        model:

                bean类;

        presenter:

                逻辑处理;

        view:

                返回成功或失败的方法;

view:

        activity

        fragment

接下来看代码

一.在AndroidManifest.xml中添加网络权限

二.在build.gradle中添加一些依赖

    //OKHTTP依赖
    implementation 'com.squareup.okhttp3:okhttp:3.12.0'
    implementation 'com.squareup.okio:okio:2.9.0'
    //OKHTTP的拦截器依赖
    implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
    //RXjava依赖
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    //gson解析
    implementation 'com.google.code.gson:gson:2.8.6'
    //GsonConverterFactory依赖
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

三.关于interfaces包中的类

Api
/**
 * @ClassName Api
 * @Description 服务器地址
 */

public class Api {
    public final static String BASE= "http://xxxxxxxxxx";
}
ApiInterface
import com.test.mvp.mvp.model.TestBean;
import java.util.HashMap;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.QueryMap;

/**
 * @ClassName ApiInterface
 * @Description 接口
 */

public interface ApiInterface {

    @GET("xxx/xxx/xxx")
    Observable testbean(@QueryMap HashMap map);

    //文件上传
    @Multipart
    @POST("xxx/xxx/xxx")
    Observable fileUp(@Part MultipartBody.Part file);

    @POST("xxx/xxx/xxx")
    Observable SignContract(@Body RequestBody json);

    @GET("xxx/xxx/xxx/{contractId}")
    Observable getSignature(@Path("contractId") int contractId);
}
RetrofitUtil
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @ClassName RetrofitUtil
 * @Description 网络请求封装
 */

public class RetrofitUtil {

    private static RetrofitUtil instance;
    private final Retrofit retrofit;

    //单例模式
    public static RetrofitUtil getInstance(){
        if (instance == null){
            synchronized (RetrofitUtil.class){
                if (instance == null){
                    instance = new RetrofitUtil();
                }
            }
        }
        return instance;
    }

    //网络请求
    private RetrofitUtil(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .connectTimeout(10000,TimeUnit.SECONDS)
                .readTimeout(10000,TimeUnit.MILLISECONDS)
                .writeTimeout(10000,TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(Api.BASE)
                .client(okHttpClient)
                .build();
    }

    public  T create(final Class service){
        return retrofit.create(service);
    }
}

四.mvp框架

        model包:

BaseModel
/**
 * @ClassName BaseModel
 * @Description TODO
 */

public class BaseModel {
    public int code;
    public String msg;
    public String message;
    public String url;
    public T data;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    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 int getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
TestBean
/**
 * @ClassName TestBean
 * @Description TODO
 */

public class TestBean {

}

        presenter包:

BasePresenter
/**
 * @ClassName BasePresenter
 * @Description TODO
 */

public class BasePresenter {
    private T view;

    public T getView(){
        return view;
    }

    public void setView(T view) {
        this.view = view;
    }

    public void onDetach(){
        if (view != null) {
            view = null;
        }
    }
}
TestPresenter
import androidx.annotation.NonNull;
import com.test.mvp.interfaces.ApiInterface;
import com.test.mvp.interfaces.RetrofitUtil;
import com.test.mvp.mvp.model.TestBean;
import com.test.mvp.mvp.view.TestView;
import java.util.HashMap;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @ClassName TestPresenter
 * @Description
 */

public class TestPresenter extends BasePresenter {
    public void getdata(HashMap hashMap){
        ApiInterface api = RetrofitUtil.getInstance().create(ApiInterface.class);
        api.testbean(hashMap).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull TestBean testBean) {
                        getView().onTestSuccess(testBean);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        getView().onTestFailure(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}

 如果是使用RequestBody的方式进行传参则使用

TestPresenter2

public class ResetPayPwdPresenter extends BasePresenter {
    public void getdata(ResetPayPwdBean_Request resetPayPwdBean_request){
        RequestBody body = null;
        MediaType parse = MediaType.parse("application/json; charset=utf-8");
        String jsonBody = GsonUtils.getInstance().toJson(resetPayPwdBean_request);
        body = RequestBody.create(parse,jsonBody);

        ApiInterface api = RetrofitUtil.getInstance().create(ApiInterface.class);
        api.resetPayPwd(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResetPayPwdBean resetPayPwdBean) {
                        getView().onResetPayPwdSuccess(resetPayPwdBean);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        getView().onResetPayPwdFailure(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}

        view包:

BaseView
/**
 * @ClassName BaseView
 * @Description TODO
 */

public interface BaseView {

}
TestView
import androidx.annotation.NonNull;

/**
 * @ClassName TestView
 * @Description
 */

public interface TestView extends BaseView {
    /**
     * 成功
     */
    void onTestSuccess(@NonNull T t);

    /**
     * 失败
     */
    void onTestFailure(String msg);
}

五:Activity中发起请求

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.test.mvp.R;
import com.test.mvp.mvp.model.TestBean;
import com.test.mvp.mvp.presenter.TestPresenter;
import com.test.mvp.mvp.view.TestView;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements TestView {

    String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        test();
    }

    //请求接口
    private void test(){
        TestPresenter testPresenter = new TestPresenter();
        testPresenter.setView(this);
        HashMap hashMap = new HashMap<>();
        hashMap.put("","");
        testPresenter.getdata(hashMap);
    }

    /**
     * 成功
     * @param testBean
     */
    @Override
    public void onTestSuccess(@NonNull TestBean testBean) {
        Log.d(TAG,"请求成功");
    }

    /**
     * 失败
     * @param msg
     */
    @Override
    public void onTestFailure(String msg) {
        Log.d(TAG,"请求失败");
    }
}

你可能感兴趣的:(android,mvp,Retrofit)