主页面布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="baway.com.mvp_test.view.MainActivity">
<EditText
android:id="@+id/etAccount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入账号" />
<EditText
android:id="@+id/etPwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码" />
<Button
android:id="@+id/btLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登陆" />
<Button
android:id="@+id/btExit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="退出登陆" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
bean包:
public class BaseBean {
public int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
public class LoginBean extends BaseBean {
/**
* datas : {"username":"andro","userid":"8","key":"c0e92b92c2e782221a78b8f457389440"}
*/
private DatasBean datas;
public DatasBean getDatas() {
return datas;
}
public void setDatas(DatasBean datas) {
this.datas = datas;
}
public static class DatasBean {
/**
* username : andro * userid : 8 * key : c0e92b92c2e782221a78b8f457389440
*/
private String username;
private String userid;
private String key;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
}
okhttp框架:
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.util.Map;
import baway.com.mvp_test.utils.NetWorkUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* Created by admin on 2017/10/16/016.
*/
public class OkHttpUtils {
//声明客户端
private OkHttpClient client;
//防止多个线程同时访问所造成的安全隐患
private volatile static OkHttpUtils utils;
private Context context;
// 子线程
private Handler handler;
// 构造方法
private OkHttpUtils(Context context) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder().addInterceptor(logging).build();
handler = new Handler(Looper.getMainLooper());
this.context = context;
}
//单例模式
public static OkHttpUtils getInstance(Context context) {
if (utils == null) {
//线程同步锁
synchronized (OkHttpUtils.class) {
if (utils == null) {
utils = new OkHttpUtils(context);
utils = utils;
}
}
}
return utils;
}
//网络请求
public void syncJsonStringByUrl(String url, final FuncJsonString callback) {
//网络判断
if (!NetWorkUtil.isNetworkAvailable(context)) {
Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();
return;
}
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "解析失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
OnSuccessJsonString(response.body().string(), callback);
}
}
});
}
// post提交表单数据
public void sendDataForClicent(String url, Map<String, String> params, final FuncJsonString callback) {
//网络判断
if (!NetWorkUtil.isNetworkAvailable(context)) {
Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();
return;
}
//表单对象,包含input开始的操作
FormBody.Builder from = new FormBody.Builder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
//装载表单值
from.add(entry.getKey(), entry.getValue());
}
}
RequestBody body = from.build();
//post提交
Request request = new Request.Builder().url(url).post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "解析失败");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
OnSuccessJsonString(response.body().string(), callback);
}
}
});
}
//返回json字符串的接口
public interface FuncJsonString {
void onResponse(String result);
}
//请求的返回是json字符串
private void OnSuccessJsonString(final String jsonValue, final FuncJsonString callback) {
handler.post(new Runnable() {
@Override
public void run() {
if (callback != null) {
try {
callback.onResponse(jsonValue);
} catch (Exception e) {
}
}
}
});
}
}
判断网络连接情况:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetWorkUtil {
// check all network connect, WIFI or mobile
public static boolean isNetworkAvailable(final Context context) {
boolean hasWifoCon = false;
boolean hasMobileCon = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfos = cm.getAllNetworkInfo();
for (NetworkInfo net : netInfos) {
String type = net.getTypeName();
if (type.equalsIgnoreCase("WIFI")) {
if (net.isConnected()) {
hasWifoCon = true;
}
}
if (type.equalsIgnoreCase("MOBILE")) {
if (net.isConnected()) {
hasMobileCon = true;
}
}
}
return hasWifoCon || hasMobileCon;
}
}
model层:
model层的作用就是进行请求数据,并将请求到的数据处理好后
通过model层的接口返回给prestener层
import android.content.Context;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
import baway.com.mvp_test.mode.bean.LoginBean;
import baway.com.mvp_test.net.Api;
import baway.com.mvp_test.net.OkHttpUtils;
/**
* Created by admin on 2017/10/24/024.
*/
public class LoginModel {
private Context context;
public LoginModel(Context context){
this.context=context;
}
public void login(String account, String pwd, final LoginListener listener){
Map<String,String> map=new HashMap<>();
map.put("username",account);
map.put("password",pwd);
map.put("client","android");
OkHttpUtils.getInstance(context).sendDataForClicent(Api.LOGIN, map, new OkHttpUtils.FuncJsonString() {
@Override
public void onResponse(String result) {
LoginBean bean=new Gson().fromJson(result,LoginBean.class);
listener.onSuccess(bean);
}
});
}
}
model层接口:
import java.io.IOException;
import baway.com.mvp_test.mode.bean.LoginBean;
/**
* Created by admin on 2017/10/24/024.
*/
public interface LoginListener {
public void onSuccess(LoginBean bean);
public void onError(IOException e);
}
prestener层:
通过m层和v层的接口进行数据的传递,从v层获取条件传递给m层请求数据;
在m层请求下数据后再通过p层返回给v层
import android.content.Context;
import java.io.IOException;
import baway.com.mvp_test.mode.LoginListener;
import baway.com.mvp_test.mode.LoginModel;
import baway.com.mvp_test.mode.bean.LoginBean;
import baway.com.mvp_test.view.IMainListener;
public class MainPresenter {
private IMainListener iMainListener;
private Context context;
private final LoginModel loginModel;
public MainPresenter(IMainListener iMainListener) {
this.context= (Context) iMainListener;
this.iMainListener=iMainListener;
loginModel=new LoginModel(context);
}
public void login(){
String acount=iMainListener.getAccount();
String pwd=iMainListener.getPwd();
loginModel.login(acount, pwd, new LoginListener() {
@Override
public void onSuccess(LoginBean bean) {
StringBuilder sb=new StringBuilder();
sb.append(" "+bean.getDatas().getUserid());
sb.append(" "+bean.getDatas().getKey());
iMainListener.setResult(sb.toString());
}
@Override
public void onError(IOException e) {
}
});
}
}
view层,也就是主界面层:
获取条件并传递给p层,在接受p层返回的请求后得到的数据并使用
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import baway.com.mvp_test.R;
import baway.com.mvp_test.presenter.MainPresenter;
public class MainActivity extends AppCompatActivity implements View.OnClickListener,IMainListener{
private EditText etAccount;
private EditText etPwd;
private Button btLogin;
private Button btExit;
private TextView tv;
private MainPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
presenter=new MainPresenter(this);
initView();
}
private void initView() {
etAccount = (EditText) findViewById(R.id.etAccount);
etPwd = (EditText) findViewById(R.id.etPwd);
btLogin = (Button) findViewById(R.id.btLogin);
btExit = (Button) findViewById(R.id.btExit);
tv = (TextView) findViewById(R.id.tv);
btLogin.setOnClickListener(this);
btExit.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btLogin:
presenter.login();
break;
case R.id.btExit:
break;
}
}
@Override
public String getAccount() {
return etAccount.getText().toString().trim();
}
@Override
public String getPwd() {
return etPwd.getText().toString().trim();
}
@Override
public void setResult(String str) {
tv.setText(str);
}
}
view层接口:
public interface IMainListener {
public String getAccount();
public String getPwd();
public void setResult(String str);
}