MVP -------簡單邏輯程式碼 -------難度2-----其中通過Handler請求資料

ren18234073466發表於2018-12-04

view層:IView介面

package com.bawei.mymvp.mvp3.view;

/**
 * 抽取View實現介面
 */
public interface IView<T> {
    /**
     * 請求成功返回的資料
     */

    void showResponseData(T data);
}

model層處理網路請求邏輯程式碼
介面:MyCallBack,封裝 返回資料到presanter層的方法
介面:IModel
實現類:IModelImpl

package com.bawei.mymvp.mvp3.callback;

/**
 * 介面儲存Model層處理網路請求的值
 * 宣告泛型為T
 * 通過對型別Object的引用來實現引數的“任意化”,“任意化”帶來的缺點是要做顯式的強制型別轉換
 * 因為“任意化”,所以在編譯的時候不會報錯,只有在執行的時候直接崩潰
 *
 * @param <T>
 */
public interface MyCallBack<T> {
    void setData(T data);
}

介面IModel

package com.bawei.mymvp.mvp3.model;


import com.bawei.mymvp.mvp3.callback.MyCallBack;

/**
 * Model介面
 */
public interface IModel {
    /**'
     * 封裝方法
     * 第一個引數:介面地址
     * 第二個引數:如果是post請求方式的話得傳引數
     * 第三個引數:處理完儲存到介面
     */
    void requestData(String url, String params, MyCallBack callBack);
}

實現類IModelImpl

package com.bawei.mymvp.mvp3.model;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.bawei.mymvp.mvp3.bean.RegBean;
import com.bawei.mymvp.mvp3.callback.MyCallBack;
import com.bawei.mymvp.mvp3.utils.HttpUtils;
import com.google.gson.Gson;

/**
 * IModel介面實現類
 * 執行網路請求,對返回的資料進行處理
 */
public class IModelImpl implements IModel {
    private MyCallBack callBack;
    /**
     * handler處理返回訊息
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    RegBean regBean = (RegBean) msg.obj;
                    if(callBack != null) {
                        callBack.setData(regBean);
                    }
                    break;
                case 1:
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 處理請求資料
     * @param url 請求的url地址
     * @param params 如果為post請求,則傳入post引數
     * @param callBack 回撥
     */
    @Override
    public void requestData(final String url, String params, final MyCallBack callBack) {
        this.callBack = callBack;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //執行網路請求
                    String jsonStr = HttpUtils.get(url);
                    Gson gson = new Gson();
                    RegBean regBean = gson.fromJson(jsonStr, RegBean.class);

                    //成功返回資料後,通過handler講訊息回給主執行緒
                    mHandler.sendMessage(mHandler.obtainMessage(0, regBean));

                } catch (Exception e) {
                    //抓住各種崩潰,全部歸於請求失敗
                    e.printStackTrace();
                    mHandler.sendMessage(mHandler.obtainMessage(0, "錯誤"));
                }
            }
        }).start();
    }
}

presenter層:view層與model層的橋樑
介面:IPresenter
實現類:IPresenterImpl

package com.bawei.mymvp.mvp3.presenter;

/**
 * P層的介面
 * 裡面簡單封裝了一個開始請求網路 開始做任務
 */
public interface IPresenter {
   void startRequest(String url,String params);
}

實現類IPresenterImpl

package com.bawei.mymvp.mvp3.presenter;

import android.util.Log;

import com.bawei.mymvp.mvp3.callback.MyCallBack;
import com.bawei.mymvp.mvp3.model.IModelImpl;
import com.bawei.mymvp.mvp3.view.IView;

/**
 * iPresenter實現介面類
 */
public class IPresenterImpl implements IPresenter {
    private IModelImpl model;
    private IView iView;

    public IPresenterImpl(IView iView) {
        this.iView = iView;
        model = new IModelImpl();
    }

    @Override
    public void startRequest(String url, String params) {
        Log.i("dj", "startRequest");
        model.requestData(url, params, new MyCallBack() {
            @Override
            public void setData(Object data) {
                iView.showResponseData(data);
            }
        });
    }

    public void onDetach(){
        if (model!=null){
            model = null;
        }
        if (iView!=null){
            iView = null;
        }
    }
}

網路請求工具類HttpUtils

package com.bawei.mymvp.mvp3.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    public static String get(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        //由一個有效的網址服務返回這個物件
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //設定請求方式
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        InputStream stream = connection.getInputStream();
        String inputStr = getInputStr(stream);
        return inputStr;
    }

    //把流轉成字串
    private static String getInputStr(InputStream stream) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));
        StringBuffer sb = new StringBuffer();
        String str = null;
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        return sb.toString();
    }
}

MvpActivity :實現IView介面重寫其中方法

package com.bawei.mymvp.mvp3;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.bawei.mymvp.R;
import com.bawei.mymvp.mvp3.bean.RegBean;
import com.bawei.mymvp.mvp3.presenter.IPresenter;
import com.bawei.mymvp.mvp3.presenter.IPresenterImpl;
import com.bawei.mymvp.mvp3.view.IView;

public class MvpActivity extends AppCompatActivity implements IView, View.OnClickListener {

    private IPresenterImpl mPresenter;
    private Button Send_Btn;
    private TextView Get_Text;
    private String mUrl = "http://www.zhaoapi.cn/user/reg?mobile=18210302397&password=123456";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mvp2);
        mPresenter = new IPresenterImpl(this);
        initView();
    }

    private void initView() {
        Send_Btn = (Button) findViewById(R.id.Send_Btn);
        Get_Text = (TextView) findViewById(R.id.Get_Text);

        Send_Btn.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDetach();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Send_Btn:
                checkPermission();
                break;
            default:
                break;
        }
    }


    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, 100);
            } else {
                startRequest();
            }
        } else {
            startRequest();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //如果requestCode匹配,切許可權申請通過
        if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startRequest();
        }
    }

    /**
     * 呼叫presenter方法,開始請求資料
     */
    private void startRequest() {
        mPresenter.startRequest(mUrl, null);
    }

    @Override
    public void showResponseData(Object data) {
        RegBean regBean = (RegBean) data;

        Get_Text.setText(String.valueOf(regBean.getData()));
        Toast.makeText(this, String.valueOf(regBean.getData()), Toast.LENGTH_SHORT).show();
    }
}

bean類:根據業務需求自己封裝

在這裡插入程式碼片

相關文章