MVP+Retrofit 一键复制

MVP需要的依赖

implementation 'com.jakewharton:butterknife:8.8.1'
implementation 'io.reactivex.rxjava2:rxjava:2.0.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'

-----------------------------------------------------------

/**
 * Created by l on 2018/10/22.
 */

public class BaseActivity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

    }

}

----------------------------------

/**
 * Created by l on 2018/10/22.
 */

public class BaseFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

}

-------------------------------

/**
 * Created by l on 2018/10/22.
 */

public class BaseLogic<V,M> {
    private WeakReference<V> mVWeakReference;
    private WeakReference<M> mMWeakReference;
    public void attach(V view,M model){
        mVWeakReference = new WeakReference<V>(view);
        mMWeakReference = new WeakReference<M>(model);
    }
    public void deatch(){
        if (mVWeakReference!=null){
            mVWeakReference.clear();
            mVWeakReference=null;
        }
        if (mMWeakReference!=null){
            mMWeakReference.clear();
            mMWeakReference=null;
        }
    }
    public V getview(){
        if (mVWeakReference==null)return null;
        return mVWeakReference.get();
    }
    public M getmodel(){
        if (mMWeakReference==null)return null;
        return mMWeakReference.get();
    }
}

---------------------------------------------

/**
 * Created by l on 2018/10/22.
 */

public abstract class BaseMvpActivity<P extends BaseLogic, M> extends BaseActivity {
    private Unbinder bind;
    public P presenter;
    private M getmodel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(intiLayout());
        bind = ButterKnife.bind(this);
        initView();
        presenter = getPresenter();
        getmodel = getmodel();
        presenter.attach(this, getmodel);
        initData();
    }


    protected abstract int intiLayout();

    protected abstract void initView();

    protected abstract M getmodel();

    protected abstract P getPresenter();

    protected abstract void initData();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bind.unbind();
        presenter.deatch();
    }
}

-------------------------------------------------------

/**
 * Created by l on 2018/10/22.
 */

public abstract class BaseMvpFragment<P extends BaseLogic,M> extends BaseFragment {
    public View view;
    public P presenter;
    public M model;
    public Unbinder bind;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(initlayout(), container, false);
        bind = ButterKnife.bind(getActivity());
        initView();
        presenter = getPresenter();
        model = getModel();
        presenter.attach(this,model);
        initData();
        return view;
    }
    protected abstract int initlayout();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract M getModel();

    protected abstract P getPresenter();

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bind!=null) bind.unbind();
        if (presenter!=null) presenter.deatch();
    }
}

--------------------------------------------------

/**
 * Created by Administrator on 2018/10/22 0022.
 */

public class BaseObserver implements Observer {
    private Disposable d;
    @Override
    public void onSubscribe(Disposable d) {
        this.d=d;
    }

    @Override
    public void onNext(Object value) {

    }

    @Override
    public void onError(Throwable e) {
        detch();
    }

    @Override
    public void onComplete() {
        detch();
    }
    private void detch() {
        if (d != null && !d.isDisposed()) {
            d.dispose();
        }
    }
}

----------------------------------------------------

/**
 * Created by l on 2018/10/22.
 */

public abstract class BaseRetrofit implements Observer {
    private Disposable d;
    @Override
    public void onSubscribe(Disposable d) {
        this.d=d;
    }

    @Override
    public void onNext(Object value) {
        next(value);
    }

    @Override
    public void onError(Throwable e) {
        error(e);
        detch();
    }

    @Override
    public void onComplete() {
        complete();
        detch();
    }

    private void detch(){
        if (d.isDisposed() && d!=null)d.dispose();
    }

    public abstract void next(Object value);
    public abstract void error(Throwable e);
    public abstract void complete();
}
-------------------------------------
interface BaseView {
}

--------------------------------------

/**
 * Created by l on 2018/10/22.
 */

public class CommonPresenter extends BaseLogic<ICommonView,ICommonModel> implements ICommonPresenter,ICommonView {

    @Override
    public void getData(int api, int intent, String... params) {
        if (getmodel()!=null){
            getmodel().getData(this,api,intent,params);
        }
    }

    @Override
    public void onResponse(Object o, int api, int intent) {
        if (getview()!=null){
            getview().onResponse(o,api,intent);
        }
    }

    @Override
    public void onCompleted() {
        if (getview()!=null){
            getview().onCompleted();
        }
    }

    @Override
    public void onError(Throwable e, int api) {
        if (getview()!=null){
            getview().onError(e,api);
        }
    }
}

--------------------------------------------------

/**
 * Created by Administrator on 2018/10/22 0022.
 */

public class HttpUtils {
    private static HttpUtils sRetrofitManager;

    private HttpUtils() {
    }

    public static HttpUtils getInstance() {
        if (sRetrofitManager == null) sRetrofitManager = new HttpUtils();
        return sRetrofitManager;
    }

    public MyServer getService(){
        return new Retrofit.Builder()
                .baseUrl(NetURL.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(getClientWithoutCache())
                .build().create(MyServer.class);
    }
    public OkHttpClient getClientWithoutCache(){
        return new OkHttpClient.Builder()
                .cache(new Cache(new File(MyApplication.getContext().getCacheDir(), "HttpCache"),10*1024*1024))
                .connectTimeout(6*1000, TimeUnit.SECONDS)
                .readTimeout(6, TimeUnit.SECONDS)
                .writeTimeout(6, TimeUnit.SECONDS)
                .addInterceptor(getLogInterceptor())
                .build();
    }

    /**
     * 网络请求log拦截器
     * @return log拦截器对象
     */

    public static HttpLoggingInterceptor getLogInterceptor(){
        //设置log拦截器拦截内容
        HttpLoggingInterceptor.Level level= HttpLoggingInterceptor.Level.BODY;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.e("------retrofit-------",message);
            }
        });
        loggingInterceptor.setLevel(level);
        return loggingInterceptor;
    }

    /**
     * 网络优先数据缓存拦截器
     * @return 拦截器对象
     */
    public static Interceptor cacheInterceptor(final Context context){
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();//获取请求
                //没有网络的时候强制使用缓存
                if (!isNetworkAvailable(context)){
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                    Log.e("睚眦","没网读取缓存");
                }
                Response response = chain.proceed(request);
                if (isNetworkAvailable(context)){
                    return response.newBuilder()
                            .removeHeader("Pragma")
                            .header("Cache-Control","public,max-age"+0)
                            .build();
                } else {
                    int maxTime = 4*24*60*30;
                    return response.newBuilder()
                            .removeHeader("Pragma")
                            .header("Cache-Control","public,only-if-cached,max-state="+maxTime)
                            .build();
                }
            }
        };
        return interceptor;
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            //ACCESS_NETWORK_STATE
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }


}
---------------------------------------------------------
public interface ICommonModel {
    void getData(ICommonView backp, int api, int intent, String... params);

}

--------------------------------------------------------

public interface ICommonPresenter {
    void getData(int api, int intent, String... params);
}

--------------------------------------------

/**
 * Created by l on 2018/10/22.
 */

public interface ICommonView <V> extends BaseView{
    void onResponse(V v, int api, int intent);
    void onCompleted();
    void onError(Throwable e, int api);
}

--------------------------------------------

/**
 * Created by l on 2018/10/22.
 */

public class MainModel extends BaseLogic implements ICommonModel{

    @Override
    public void getData(ICommonView backp, int api, int intent, String... params) {
    }
}

-------------------------------------------------------

/**
 * Created by Administrator on 2018/10/22 0022.
 */

public class ModelUtils {
    public static<T> void getDataM(final ICommonView backP, final int api, final int intent, Observable<T> observable){
        observable.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new BaseObserver(){
                    @Override
                    public void onNext(Object value) {
                        super.onNext(value);
                        Log.e("values",value+"");
                        backP.onResponse(value, api, intent);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        backP.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        backP.onError(e, api);
                    }
                });
    }

}

------------------------------------------

/**
 * Created by l on 2018/10/22.
 */

public class MyApplication extends Application {
    public static MyApplication sMyApplication;
    @Override
    public void onCreate() {
        super.onCreate();
        sMyApplication=this;
    }
    public static MyApplication getMyApplication(){
        return sMyApplication;
    }
    public static Context getContext(){
        return sMyApplication.getApplicationContext();
    }
}

---------------------------------------

//接口不变前缀

public class NetURL {
   
    public static String BASE_URL="接口不变前缀";
}

------------------------------------

/**
 * Created by Administrator on 2018/10/22 0022.
 */

public interface MyServer {

    @GET("后缀")
    Observable<Project> getproject();
}

------------------------------

/**
 * Created by Administrator on 2018/10/22 0022.
 */

public class ApiConfig {
    public final static int SHOUYE_ONE=0;
   

}

------------------------------

public class ProjectModel extends BaseLogic implements ICommonModel {
    private MyServer getService(){
        return  HttpUtils.getInstance().getService();
    }
    @Override
    public void getData(ICommonView backp, int api, int intent, String... params) {
        switch (api) {
            case ApiConfig.SHOUYE_ONE: {
                getproject(backp, api, intent,params);
                break;
            }

        }
    }

    private void getproject(ICommonView backp, int api, int intent, String[] params) {
        ModelUtils.getDataM(backp,api,intent  ,getService().getproject());
    }



}

-------------------------------------------

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值