阅读 1346

基于Android+ Retrofit+MVP基础架构封装

前言

从事android开发也有一段时间了,如何封装基础架构在我们的开发中是必不可缺的技能。今天给大家分享的是基于retrofit+mvp封装的基础架构,适用于新手,大佬请忽略…………。其目的是做一个资源整合,如有不对之处请指教!

第一章:公共方法封装

一、封装 RetrofitWrapper.class

1.新建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) {
                //打印retrofit日志
                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){
            //不需要错误重连
            builder.retryOnConnectionFailure(false);
        }else {
            //错误重连
            builder.retryOnConnectionFailure(true);
        }
        //获取实例
        mRetrofit = new Retrofit
                //设置OKHttpClient,如果不设置会提供一个默认的
                .Builder()
                //设置baseUrl
                .baseUrl(mAddress)
                //添加转换器Converter(将json 转为JavaBean),用来进行响应数据转化(反序列化)的ConvertFactory
                .addConverterFactory(GsonConverterFactory.create())
                //添加自定义转换器
//                .addConverterFactory(JsonConverterFactory.create())
                //添加rx转换器,用来生成对应"Call"的CallAdapter的CallAdapterFactory
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(build)
                .build();
    }
    /**
     * 初始化完全信任的信任管理器
     */
    @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() {
                    return new 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();
        }
    }


    /**
     * 设置读取超时时间,连接超时时间,写入超时时间值
     */
    private void initTimeOut() {
        builder.readTimeout(20000, TimeUnit.SECONDS);
        builder.connectTimeout(10000, TimeUnit.SECONDS);
        builder.writeTimeout(20000, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
    }
    public <T> T create(final  Class<T> tClass)
    {
        return mRetrofit.create(tClass);
    }
}复制代码

二、公共接口MvpView创建

public interface MvpView {
    Context getContext();
    void showLoadingDialog();
    void dismissLoadingDialog();
    void showLoadingBar();
    void dismissLoadingBar();
    void clearLoading();
}复制代码

三、公共接口BaseView 创建

public interface BaseView extends   MvpView{
}复制代码

四、公共抽象类MvpPresenter 创建

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() {
        return baseView != null;
    }


    public Context getContext() {
        return context;
    }
    public void showLoadingDialog() {
        if (baseView != null) {
            baseView.showLoadingDialog();
        }
    }
    public void dismissLoadingDialog() {
        if (baseView != null) {
            baseView.dismissLoadingDialog();
        }
    }
    public void showLoadingBar() {
        if (baseView != null) {
            baseView.showLoadingBar();
        }
    }
    public void dismissLoadingBar() {
        if (baseView != null) {
            baseView.dismissLoadingBar();
        }
    }


}复制代码

五、公共抽象类MvpActivity 创建

public abstract class MvpActivity <P extends MvpPresenter> extends
        AppCompatActivity implements
        MvpView, View.OnClickListener {
    public  P presenter;
    private static Activity mCurrentActivity;// 对所有activity进行管理
    public static List<Activity> mActivities = new LinkedList<Activity>();
    protected Bundle savedInstanceState;
    private  static  long mPreTime;

    /**
     * 获取布局资源文件
     */
    protected abstract int getLayoutId();
    /**
     * 初始化presenter
     */
    @Nullable
    protected abstract P initPresenter();
    @Override
    public void onClick(View view) {

    }

    @Override
    public Context getContext() {
        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());
        }
        //实例化P Presenter
        presenter=initPresenter();
        if(presenter!=null)
        {
            //实例化
            presenter.attach(this);
        }
        initialize();
    }

    private void initWindow() {
    }
    protected void initialize() {
        initView();
        loadData();
    }

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

    @Override
    public void onBackPressed() {
//        if(mCurrentActivity instanceof MainActivity)
//        {
//            //如果是主页面
//            if (System.currentTimeMillis() - mPreTime > 2000) {// 两次点击间隔大于2秒
//
//                Toast.makeText(MyApp.getContext(), "再按一次,退出应用", Toast.LENGTH_SHORT).show();
//                mPreTime = System.currentTimeMillis();
//                return;
//            }
//            exitApp();
        }
//        if(mCurrentActivity instanceof LoginActivity)
//        {
//            exitApp();
//        }
//        super.onBackPressed();//finish()
//    }
public static void exitApp() {

    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();
        }

    }
}复制代码

六、公共抽象方法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();
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    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 void showLoadingDialog() {
        super.showLoadingDialog();
        if(NetWork)
        {
            netWorks = "网络不可用^^";
        }
        else {
            netWorks = "加载中…";
        }
        if(myLoadingDialog==null)
        {
         myLoadingDialog =new MyLoadingDialog(this);
            myLoadingDialog.setMessage(netWorks);
            myLoadingDialog.show();
        }


    }

    @Override
    public void dismissLoadingDialog() {
        if(myLoadingDialog!=null)
        {
        myLoadingDialog.dismiss();
        }
    }

    @Override
    public void clearLoading() {
        //使用过后将其回收
    if(myLoadingDialog!=null)
    {
        myLoadingDialog.dismiss();
        myLoadingDialog=null;
    }
    }

}复制代码

第二章 Activity页面实现

1.自定义数据回调接口:

public interface MainView  extends MvpView {

void  getUserArticleList(ArticleListBean articleListBean);
}
复制代码

2.自定义请求网络数据,并实现网络数据返回

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();
                   }
               });
   }

}复制代码

3.Activity层实现

public class MainActivity extends BaseActivity<MainPresenter> implements MainView {
    ListView mListView;
    TextView tvTitle;
    private ListViewAdapter mTKTAdapter;
    private List<ItemBean> mTKTData;//这个集合保存的即是相应的EditText中你填写的值

    @Override
    protected int getLayoutId() {
        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("你好");
            mTKTData.add(itemBean);
        }
        mTKTAdapter = new ListViewAdapter(this, mTKTData);
        mListView.setAdapter(mTKTAdapter);
//        mTKTAdapter.notifyDataSetChanged();

        presenter.list(1);
    }

    @Override
    public void getUserArticleList(ArticleListBean articleListBean) {
        Log.i("测试",articleListBean.getData().getDatas().size()+"sss");
        tvTitle.setText(articleListBean.getData().getDatas().size()+"sss");
    }
}复制代码

4.网络请求ServiceApis

public interface ServiceApi {

    @GET("/mobileServer/mobile/login.smvc?")
    Observable<LoginBean> getCategoryDate(@QueryMap Map<String, String> map);
    //相当于 &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);


}复制代码

第三章 Fragment基础框架封装

1.MvpFragment

public abstract class MvpFragment<T extends MvpPresenter> extends LazyFragment
        implements MvpView, View.OnClickListener {
    /**
     *T:表示任意类型对象
     */
    protected T presenter;
    protected abstract T initPresenter();
    /**
     * 获取布局资源文件
     *
     * @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 void onDestroy() {
        super.onDestroy();
        if(presenter!=null)
        {
            presenter.detach();
        }
    }
}复制代码

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();

    }

    /**
     * 通过bundle 数据传递
     * @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 void onDestroyView() {
        clearLoading();
        super.onDestroyView();

//        if (isRegisterEventBus()) {
//            EventBus.getDefault().unregister(this);
//        }
//        if (mUnbinder != null) {
//            mUnbinder.unbind();
//        }
    }

    @Override
    public void showLoadingDialog() {
        if(NetWork)
        {
            netWorks = "网络不可用^^";
        }
        else {
            netWorks = "加载中…";
        }
        if(myLoadingDialog==null)
        {
            myLoadingDialog =new MyLoadingDialog(getContext());
            myLoadingDialog.setMessage(netWorks);
            myLoadingDialog.show();
        }
    }
    @Override
    public void dismissLoadingDialog() {
        if(myLoadingDialog!=null)
        {
            myLoadingDialog.dismiss();
        }
    }
    @Override
    public void clearLoading() {
        //使用过后将其回收
        if(myLoadingDialog!=null)
        {
            myLoadingDialog.dismiss();
            myLoadingDialog=null;
        }
    }
}复制代码

end:源码地址奉上:

github.com/guoxuxiong/…

如有不对之处请指正,谢谢!!


文章分类
Android
文章标签