Android常用架构之MVP

MVC由Model、View、Control组成。
Model数据模型,提供数据
View视图模型,提供视图展示
Control控制器,负责控制Model和View通信

MVC在Android中的应用,如下图,Activity为Control,XML为View,请求网络数据模块为Model。View箭头指向Control意为传递数据,那就是Control获取View的数据传递给Model来请求网络,请求到的数据直接传递给View来显示,这是一条主线。还有一条就是底部这两个箭头,也就是说Model可以不通过Control,直接获取View的数据,然后再返回结果数据给View。

Android常用架构之MVP

MVP由Model、View、Presenter组成。
Model数据模型,提供数据
View视图模型,提供视图展示
Presenter主持者,负责逻辑处理

MVP与MVC最明显的区别就在于Presenter和Control了。如下图,Presenter传递数据给Model,Model得到数据来请求网络,再返回数据给Presenter,Presenter再把得到的Model数据传递给View显示。MVP整体的一个流程就是这样。相比MVC来说,Model和View互相不干涉,达到完全解耦

Android常用架构之MVP

估计上面文字性的解释都听得有点晕,那我们就拿个例子来实战一下吧

下面和大家一起完成一个简单查询快递信息的例子,里面用到了当下最流行的架构RxJava+Retrofit+MVP+OkHttp,非常值得大家一学

配置环境

在builde.gradle里面添加

compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.1.6'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

在AndroidManifest.xml添加所需权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

初始化配置Retrofit

public class MainApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //初始化retrofitUtils
        RetrofitUtils.getInstance().initOkHttp(this);
    }
}

在MainApp中初始化Retrofit,设置超时和baseUrl,添加了日志拦截以及RxJava和数据解析,并暴露一个getRetrofit()方法供需要的地方调用

public class RetrofitUtils {
    private Retrofit retrofit;
    private String baseUrl = "http://www.kuaidi100.com/";
    private static class SingleLoader{
        private static final RetrofitUtils INSTANCE = new RetrofitUtils();
    }
    public static RetrofitUtils getInstance(){
        return SingleLoader.INSTANCE;
    }
    public void initOkHttp(@NonNull Context context){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10000L,TimeUnit.MILLISECONDS)       //设置连接超时
                .readTimeout(10000L,TimeUnit.MILLISECONDS)          //设置读取超时
                .writeTimeout(10000L, TimeUnit.MILLISECONDS)         //设置写入超时
                .cache(new Cache(context.getCacheDir(),10 * 1024 * 1024))   //设置缓存目录和10M缓存
                .addInterceptor(interceptor)    //添加日志拦截器(该方法也可以设置公共参数,头信息)
                .build();
        retrofit = new Retrofit.Builder()
                .client(client)        //设置OkHttp
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create()) //  添加数据解析ConverterFactory
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())   //添加RxJava
                .build();
    }
    public Retrofit getRetrofit(){
        return retrofit;
    }
}

Model

public interface PostSearchModel {
    /**
     * 请求快递信息
     * @param type 快递类型
     * @param postid 快递单号
     * @param callback 结果回调
     */
    void requestPostSearch(String type,String postid,PostSearchCallback callback);
    interface PostSearchCallback{
        void requestPostSearchSuccess(PostQueryInfo postQueryInfo);
        void requestPostSearchFail(String failStr);
    }
}

创建这个PostSearchModel接口,方便后期可以不修改之前代码灵活切换多种实现方式

public interface PostServiceBiz {
    @POST("query")
    Observable<PostQueryInfo> searchRx(@Query("type") String type, @Query("postid") String postid);
}
public class PostQueryInfo {
    private String message;
    private String nu;
    private String ischeck;
    private String com;
    private String status;
    private String condition;
    private String state;
    private List<DataBean> data;
    public static class DataBean {
        private String time;
        private String context;
        private String ftime;
    }
}

PostQueryInfo没有添加get和set方法,大家自行快捷键了
PostSearchModelImpl实现上面PostSearchModel接口,利用上一篇文章里学的Retrofit结合RxJava来请求网络
这里传了PostSearchCallback回调函数,成功或者失败都通过回调函数返回,完全不需要考虑其它

public class PostSearchModelImpl implements PostSearchModel {
    @Override
    public void requestPostSearch(String type, String postid, final PostSearchCallback callback) {
        RetrofitUtils.getInstance()
                .getRetrofit()
                .create(PostServiceBiz.class)
                .searchRx(type,postid)
                //访问网络切换异步线程
                .subscribeOn(Schedulers.io())
                //响应结果处理切换成主线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<PostQueryInfo>() {
                    @Override
                    public void onCompleted() {
                        //请求结束回调
                    }
                    @Override
                    public void onError(Throwable e) {
                        //错误回调
                        callback.requestPostSearchFail(e.getMessage());
                    }
                    @Override
                    public void onNext(PostQueryInfo postQueryInfo) {
                        //成功结果返回
                        callback.requestPostSearchSuccess(postQueryInfo);
                    }
                });
    }
}

View

activity_main.xml主界面布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".ui.MainActivity"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="快递公司名:"/>
        <EditText
            android:id="@+id/post_name_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="yuantong"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="快 递  单 号:"
            />
        <EditText
            android:id="@+id/post_id_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="500379523313"/>
    </LinearLayout>
    <Button
        android:id="@+id/post_search_bn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询"/>
    <ListView
        android:id="@+id/post_list_lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:listSelector="@null"
        android:background="@null"/>
</LinearLayout>

view_item_logistics.xml
listview适配器的item布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:orientation="vertical"
    android:padding="15dp">
    <TextView
        android:id="@+id/tv_conent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#8f8f8f"
        android:textSize="14sp"
        android:text="【深圳市】广东分公司已出发" />
    <TextView
        android:layout_marginTop="13dp"
        android:id="@+id/tv_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#8f8f8f"
        android:textSize="12sp"
        android:layout_marginBottom="13dp"
        android:paddingLeft="6dp"
        android:text="2016-05-03 18:23" />
</LinearLayout>

ListView适配器

public class LogisticsAdapter extends BaseAdapter {
    private List<PostQueryInfo.DataBean> datas;
    private LayoutInflater inflater;
    public LogisticsAdapter(Context context, List<PostQueryInfo.DataBean> datas) {
        this.datas = datas;
        inflater = LayoutInflater.from(context);
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        PostQueryInfo.DataBean data = datas.get(i);
        view = inflater.inflate(R.layout.view_item_logistics, null);
        TextView tv_content= (TextView) view.findViewById(R.id.tv_conent);
        TextView tv_date= (TextView) view.findViewById(R.id.tv_date);
        tv_content.setText(data.getContext().replace("[","【").replace("]","】"));
        tv_date.setText(data.getTime());
        return view;
    }
    @Override
    public int getCount() {
        return datas != null ? datas.size() : 0;
    }
    @Override
    public Object getItem(int i) {
        return datas.get(i);
    }
    @Override
    public long getItemId(int i) {
        return i;
    }
}

BaseView提供通用显示和隐藏加载框,如果有通用的方法都可以在写在这里面

public interface BaseView {
    void showProgressDialog();    
    void hideProgressDialog();
}

MainView接口继承提供MainActivity所有需要更新界面UI的方法

public interface MainView extends BaseView{
    void updateListUI(PostQueryInfo postQueryInfo);
    void errorToast(String message);
}

BaseActivity实现BaseVew所有接口方法

public class BaseActivity extends Activity implements BaseView{
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("查询中...");
    }
    @Override
    public void showProgressDialog(){
        if(progressDialog!=null){
            progressDialog.show();
        }
    }
    @Override
    public void hideProgressDialog(){
        if(progressDialog!=null&&progressDialog.isShowing()){
            progressDialog.dismiss(); 
       }
    }
}

MainActivity继承BaseActivity实现MainView所有方法供PostPresenter调用,点击查询按钮通过实例化的PostPresenter,调用相关方法,后面的事情就全部交给PostPresenter去处理了,在activity销毁的时候调用postPresenter.detach()防止内存泄漏

public class MainActivity extends BaseActivity implements View.OnClickListener, MainView {
    private EditText post_name_et;
    private EditText post_id_et;
    private ListView post_list_lv;
    private Button post_search_bn;
    private PostPresenter postPresenter;
    private List<PostQueryInfo.DataBean> dataArray = new ArrayList<>();
    private LogisticsAdapter logisticsAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initEvent();
    }
    private void initView() {
        post_name_et = (EditText) findViewById(R.id.post_name_et);
        post_id_et = (EditText) findViewById(R.id.post_id_et);
        post_list_lv = (ListView) findViewById(R.id.post_list_lv);
        post_search_bn = (Button) findViewById(R.id.post_search_bn);
    }
    private void initData() {
        logisticsAdapter = new LogisticsAdapter(getApplicationContext(),dataArray);
        postPresenter = new PostPresenter(this);
        post_list_lv.setAdapter(logisticsAdapter);
    }
    private void initEvent() {
        post_search_bn.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.post_search_bn:
           postPresenter.requestHomeData(post_name_et.getText().toString(),post_id_et.getText().toString());
                break;
        }
    }
    @Override
    public void updateListUI(PostQueryInfo postQueryInfo) {
        dataArray.clear();
        dataArray.addAll(postQueryInfo.getData());
        logisticsAdapter.notifyDataSetChanged();
    }
    @Override
    public void errorToast(String message) {
        Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
    }
    @Override
    protected void onDestroy(){
        //防止activity销毁,postPresenter对象还存在造成的内存泄漏
        if(postPresenter!=null) postPresenter.detach();
        super.onDestroy();
    }
}

Presenter

BasePresenter基类,提供了一个通用view对象,以及初始化和销毁view对象的方法

public abstract class BasePresenter<T>{
    public T mView;
    public void attach(T view){
        this.mView = view;
    }
    public void detach(){
        mView = null;
    }
}

PostPresenter在构造函数中通过基类attach的方法初始化MainActivity提供的view对象,实例化PostSearchModelImpl对象,通过它提供的方法来请求网络数据,在成功和失败回调的函数里,可以做一些逻辑处理,通过view对象更新相应的UI

public class PostPresenter extends BasePresenter<MainView>{
    private PostSearchModel postSearchModel;
    public PostPresenter(MainView mainView){
        attach(mainView);
        postSearchModel = new PostSearchModelImpl();
    }
    public void requestHomeData(String type,String postid){
        if(postSearchModel == null||mView == null)
            return;
        mView.showProgressDialog();
        postSearchModel.requestPostSearch(type, postid, new PostSearchModel.PostSearchCallback() {
            @Override
            public void requestPostSearchSuccess(PostQueryInfo postQueryInfo) {
                mView.hideProgressDialog();
                if(postQueryInfo!=null&&"ok".equals(postQueryInfo.getMessage())) {
                    mView.updateListUI(postQueryInfo);
                }
            }
            @Override
            public void requestPostSearchFail(String failStr) {
                mView.hideProgressDialog();
                mView.errorToast(failStr);
            }
        });
    }
}

到这里全部代码基本都已编写完,代码的结构如下图:

Android常用架构之MVP

下面就运行程序看看效果吧,快递公司名和快递单号默认填写上去了,大家只需要点击查询,结果和下面图片一样就说明成功了

Android常用架构之MVP

为什么没有直接提供一个可以运行的DEMO出来,原因很简单就是希望大家能够跟着一步一步学习,然后动手慢慢边敲代码边理解,最后敲完运行成功,应该就会更加理解MVP了。

相关推荐