preface

We’ve been working on Android for a while, and how to encapsulate infrastructure is an essential skill in our development. Today to share with you is based on retrofit+ MVP encapsulated infrastructure, suitable for beginners, big guys please ignore ………… . Its purpose is to do a resource conformity, if have wrong place please instruct!

Chapter 1: Public method encapsulation

Encapsulate retroFitWrapper.class

1. Create a new class retroFitWrapper.class

public class RetrofitWrapper {
    private Retrofit mRetrofit;
    private final OkHttpClient.Builder builder;
    HttpLoggingInterceptor loggingInterceptor;
    private  String mAddress="https://www.wanandroid.com/";
    public static RetrofitWrapper getInstance()
    {
        RetrofitWrapper instance;
        synchronized (RetrofitWrapper.class)
        {
        instance=new RetrofitWrapper();
        }
        return  instance;
    }

    private  RetrofitWrapper() { builder = new OkHttpClient.Builder(); LoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor).Logger() {
            @Override
            public void log(String message) {// Print the retrofit Log log.i ("retrofitLog: ", message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(loggingInterceptor);//
        OkHttpClient build = builder.build();
        initBuilder(mAddress,build);
        }

    private void initBuilder(String mAddress, OkHttpClient build) {
        initSSL();
        initTimeOut();

        if(BuildConfig. DEBUG) {/ / don't need a mistake reconnection builder. RetryOnConnectionFailure (false);
        }else{/ / error reconnection builder. RetryOnConnectionFailure (true); } // Get instance mRetrofit = new Retrofit // set OKHttpClient, if not set it will provide a default.builder () // set baseurl.baseurl (mAddress) // Add Converter(convert json to JavaBean), Used to carry out the response data conversion (deserialization) ConvertFactory. AddConverterFactory (GsonConverterFactory. The create ()) / / / / add custom converter AddConverterFactory (JsonConverterFactory. The create ()) / / add rx converter, used to generate the corresponding"Call"The CallAdapter CallAdapterFactory. AddCallAdapterFactory (RxJava2CallAdapterFactory. The create ()). The client (build). The build (); } /** * Initialize a fully trusted trust manager */ @suppresswarnings ("deprecation")
    private void initSSL() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    returnnew X509Certificate[]{}; }}}; SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true; }}); } catch (Exception e) { e.printStackTrace(); }} /** * Set read timeout, connection timeout, and write timeout values */ private voidinitTimeOut() { builder.readTimeout(20000, TimeUnit.SECONDS); builder.connectTimeout(10000, TimeUnit.SECONDS); builder.writeTimeout(20000, TimeUnit.SECONDS); / / error reconnection builder. RetryOnConnectionFailure (true);
    }
    public <T> T create(final  Class<T> tClass)
    {
        returnmRetrofit.create(tClass); }}Copy the code

Create public interface MvpView

public interface MvpView {
    Context getContext();
    void showLoadingDialog();
    void dismissLoadingDialog();
    void showLoadingBar();
    void dismissLoadingBar();
    void clearLoading();
}Copy the code

Create the public interface BaseView

public interface BaseView extends   MvpView{
}Copy the code

Create a public abstract MvpPresenter class

public abstract class MvpPresenter <V extends  MvpView> {
    protected Context context;
    private V baseView;

    public void attach(V baseView)
    {
    this.baseView=baseView;
    }

    public void detach() {
        baseView = null;
        context = null;
    }
    public  V getBaseView() {return baseView;
    }
    public boolean isAttach() {
        returnbaseView ! = null; } public ContextgetContext() {
        return context;
    }
    public void showLoadingDialog() {
        if(baseView ! = null) { baseView.showLoadingDialog(); } } public voiddismissLoadingDialog() {
        if(baseView ! = null) { baseView.dismissLoadingDialog(); } } public voidshowLoadingBar() {
        if(baseView ! = null) { baseView.showLoadingBar(); } } public voiddismissLoadingBar() {
        if(baseView ! = null) { baseView.dismissLoadingBar(); }}}Copy the code

Create the public abstract MvpActivity class

public abstract class MvpActivity <P extends MvpPresenter> extends AppCompatActivity implements MvpView, View.OnClickListener { public P presenter; private static Activity mCurrentActivity; Public static List< activity > mActivities = new LinkedList< activity >(); public static List< activity > mActivities = new LinkedList< activity >(); protected Bundle savedInstanceState; private static long mPreTime; */ protected abstract int getLayoutId(); /** * Initialize presenter */ @nullable protected abstract P initPresenter(); @Override public void onClick(View view) { } @Override public ContextgetContext() {
        return null;
    }

    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void dismissLoadingDialog() {

    }

    @Override
    public void showLoadingBar() {

    }

    @Override
    public void dismissLoadingBar() {

    }

    @Override
    public void clearLoading() {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.savedInstanceState = savedInstanceState;
        synchronized (mActivities) {
            mActivities.add(this);
        }
        initWindow();
        if(getLayoutId()>0)
        {
            setContentView(getLayoutId()); } // instantiate P Presenter Presenter =initPresenter();if(presenter! =null) {// instantiate presenter. Attach (this); } initialize(); } private voidinitWindow() {
    }
    protected void initialize() {
        initView();
        loadData();
    }

    protected abstract void initView();
    protected abstract void loadData();

    @Override
    public void onBackPressed() {
//        if(mCurrentActivity instanceof MainActivity) {// // if the main page //if(system.currentTimemillis () -mpretime > 2000) {// Click more than 2 seconds apart // // totoast. MakeText (myApp.getContext (),"Press again to exit the app.", Toast.LENGTH_SHORT).show();
//                mPreTime = System.currentTimeMillis();
//                return; / / / /}exitApp(); } / /if(mCurrentActivity instanceof LoginActivity)
//        {
//            exitApp(); // } // super.onBackPressed(); //finish() // } public static voidexitApp() {

    ListIterator<Activity> iterator = mActivities.listIterator();

    while (iterator.hasNext()) {
        Activity next = iterator.next();
        next.finish();
    }
}
    @Override
    protected void onResume() {
        super.onResume();
        mCurrentActivity = this;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mCurrentActivity = null;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        synchronized (mActivities)
        {
            mActivities.remove(this);
        }
        if(presenter! =null) { presenter.detach(); }}}Copy the code

Public abstract method BaseActivity

public abstract  class BaseActivity<P extends MvpPresenter> extends MvpActivity<P>{
    public BaseActivity mContext;
    private  boolean NetWork=false;
    private String netWorks;
    MyLoadingDialog myLoadingDialog;

    @Override
    protected void initialize() { super.initialize(); // mUnbinder = ButterKnife.bind(this); MContext =this; NetworkUtils networkUtils=new NetworkUtils(this);if(! networkUtils.isConnected()){ NetWork=true;
        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if(mUnbinder ! = null) { // mUnbinder.unbind(); // } clearLoading(); **/ public void startActivityBundle(Class<? > cls, Bundle bundle) { Intent intent = new Intent(); intent.setClass(this, cls);if(bundle ! = null) { intent.putExtras(bundle); } startActivity(intent); } @Override public voidshowLoadingDialog() {
        super.showLoadingDialog();
        if(NetWork)
        {
            netWorks = "Network unavailable ^^";
        }
        else {
            netWorks = "Loading...";
        }
        if(myLoadingDialog==null)
        {
         myLoadingDialog =new MyLoadingDialog(this);
            myLoadingDialog.setMessage(netWorks);
            myLoadingDialog.show();
        }


    }

    @Override
    public void dismissLoadingDialog() {
        if(myLoadingDialog! =null) { myLoadingDialog.dismiss(); } } @Override public voidclearLoading() {// Recycle it after useif(myLoadingDialog! =null) { myLoadingDialog.dismiss(); myLoadingDialog=null; }}}Copy the code

Chapter 2 Implementation of the Activity page

1. Custom data callback interface:

public interface MainView  extends MvpView {

void  getUserArticleList(ArticleListBean articleListBean);
}
Copy the code

2. Customize the request for network data and return the network data

public class MainPresenter extends MvpPresenter<MainView> {
    final ServiceApi serviceApi = RetrofitWrapper.getInstance().create(ServiceApi.class);

    public  void list(int page)
   {
       showLoadingDialog();
       serviceApi.getUserArticleList(page)
               .subscribeOn(Schedulers.newThread())
               .subscribeOn(AndroidSchedulers.mainThread())
               .subscribe(new Observer<ArticleListBean>() {
                   @Override
                   public void onSubscribe(Disposable d) {

                   }

                   @Override
                   public void onNext(ArticleListBean mJsonObject) {
                       Log.i("ssssssssssss",mJsonObject.getData().getDatas().size()+"");
//                       tvTitle.setText(mJsonObject.getData().getDatas().size()+"");
                       getBaseView().getUserArticleList(mJsonObject);
                   }

                   @Override
                   public void onError(final Throwable e) {
                       Log.i("ssssssssssss",e.toString());
                       dismissLoadingDialog();
                   }

                   @Override
                   public void onComplete() {
                       Log.i("ssssssssssss"."******onComplete****"); dismissLoadingDialog(); }}); }}Copy the code

3. The Activity layer implementation

public class MainActivity extends BaseActivity<MainPresenter> implements MainView { ListView mListView; TextView tvTitle; private ListViewAdapter mTKTAdapter; private List<ItemBean> mTKTData; // This collection will hold the corresponding EditText value you filled in @override protected intgetLayoutId() {
        return R.layout.activity_main;
    }

    @Nullable
    @Override
    protected MainPresenter initPresenter() {
        return new MainPresenter();
    }


    @Override
    protected void initView() {
        tvTitle=findViewById(R.id.tvTitle);
        mListView=findViewById(R.id.list_item);
    }

    @Override
    protected void loadData() {

        mTKTData = new ArrayList<ItemBean>();
        for(int i=0; i<10; i++){ ItemBean itemBean=new ItemBean(); itemBean.setText("Hello");
            mTKTData.add(itemBean);
        }
        mTKTAdapter = new ListViewAdapter(this, mTKTData);
        mListView.setAdapter(mTKTAdapter);
//        mTKTAdapter.notifyDataSetChanged();

        presenter.list(1);
    }

    @Override
    public void getUserArticleList(ArticleListBean articleListBean) {
        Log.i("Test",articleListBean.getData().getDatas().size()+"sss");
        tvTitle.setText(articleListBean.getData().getDatas().size()+"sss"); }}Copy the code

4. Network request ServiceApis

public interface ServiceApi {

    @GET("/mobileServer/mobile/login.smvc?") Observable<LoginBean> getCategoryDate(@QueryMap Map<String, String> map); // equivalent to &key=? @POST("/user/register")
    Observable<User> register(@Query("name") String name,
                                     @Query("password") String password);
    @GET("user_article/list/{page}/json")
    Observable<ArticleListBean> getUserArticleList(@Path("page") int page);


}Copy the code

Chapter 3 Fragment basic framework encapsulation

1.MvpFragment

public abstract class MvpFragment<T extends MvpPresenter> extends LazyFragment implements MvpView, View.OnClickListener {/** *T: specifies an object of any type */ protected T presenter; protected abstract T initPresenter(); /** * Get the layout resource file ** @return int
     */
    @Override
    @LayoutRes
    protected abstract int getLayoutRes();
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        attachPresenter();
        initialize();
    }

    protected void initialize() {
    initView();
    loadData();
    }
    @Override
    public Context getContext() {
        return getActivity();
    }

    public Fragment getFragment() {
        return this;
    }
    protected abstract void loadData();

    protected abstract void initView();

    private void attachPresenter() {
        if(presenter==null)
        {
        presenter=initPresenter();
        }
        if(presenter! =null) { presenter.attach(this); } } @Override protected void onVisible(boolean isFirstVisible) { super.onVisible(isFirstVisible); attachPresenter(); } @Override public voidonDestroy() {
        super.onDestroy();
        if(presenter! =null) { presenter.detach(); }}}Copy the code

2.BaseFragment

public abstract  class BaseFragment<P extends MvpPresenter>extends MvpFragment<P> {
    private  boolean NetWork=false;
    MyLoadingDialog myLoadingDialog;
    private String netWorks;
    @Override
    protected void initialize() {
//        if(getRootView() ! = null) { // mUnbinder = ButterKnife.bind(this, getRootView()); / / / /}if (isRegisterEventBus()) {
//            EventBus.getDefault().register(this);
//        }
        NetworkUtils networkUtils=new NetworkUtils(getContext());
        if(! networkUtils.isConnected()){ NetWork=true; } super.initialize(); @param CLS * @param bundle */ public void startActivityBundle(Class<? > cls, Bundle bundle) { Intent intent = new Intent(); intent.setClass(getContext(), cls);if(bundle ! = null) { intent.putExtras(bundle); } startActivity(intent); } @Override public voidonDestroyView() {
        clearLoading();
        super.onDestroyView();

//        if(isRegisterEventBus()) { // EventBus.getDefault().unregister(this); / / / /}if(mUnbinder ! = null) { // mUnbinder.unbind(); // } } @Override public voidshowLoadingDialog() {
        if(NetWork)
        {
            netWorks = "Network unavailable ^^";
        }
        else {
            netWorks = "Loading...";
        }
        if(myLoadingDialog==null)
        {
            myLoadingDialog =new MyLoadingDialog(getContext());
            myLoadingDialog.setMessage(netWorks);
            myLoadingDialog.show();
        }
    }
    @Override
    public void dismissLoadingDialog() {
        if(myLoadingDialog! =null) { myLoadingDialog.dismiss(); } } @Override public voidclearLoading() {// Recycle it after useif(myLoadingDialog! =null) { myLoadingDialog.dismiss(); myLoadingDialog=null; }}}Copy the code

End: Source address on:

Github.com/guoxuxiong/…

If there is any wrong, please correct, thank you!