2018年01月18日 20:55:51 zz19970108 阅读数:263
//1、导入相应的依赖
//retrofit2的依赖 compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0' //rxJava2的依赖 compile 'io.reactivex.rxjava2:rxandroid:2.0.1' // Because RxAndroid releases are few and far between, it is recommended you also // explicitly depend on RxJava's latest version for bug fixes and new features. compile 'io.reactivex.rxjava2:rxjava:2.1.7'
//拦截器
implementation 'com.squareup.okhttp3:logging-interceptor:+'
//2、创建MVP模式所需要的包
-------------------------网络请求工具类-------------------
//3、创建ServiceAPi
public interface ServiceApi { //登录 @GET(Urls.LOGIN_URL) Observablelogin(@Query("mobile") String mobile, @Query("password") String password); //注册 @GET(Urls.REGISTER_URL) Observable register(@Query("mobile") String mobile, @Query("password") String password); }
------------创建RetrofitHelper类------------------
public class RetrofitHelper { private static OkHttpClient okHttpClient; private static HttpUtils httpUtils; static { initOkHttpClient(); } /** * 初始化OkHttpClient */ private static void initOkHttpClient() { if (okHttpClient == null) { synchronized (RetrofitHelper.class) { if (okHttpClient == null) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClient = new OkHttpClient.Builder() .addInterceptor(logging)
.addInterceptor(new MyInterceptor())
.build();
} } } } /** * 定义一个泛型方法 * * @param tClass * @param url * @param* @return */ public static T createAPI(Class tClass, String url) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); return retrofit.create(tClass); } public static HttpUtils getHttpUtils() { if (httpUtils == null) { synchronized (HttpUtils.class) { if (httpUtils == null) { httpUtils = createAPI(HttpUtils.class, API.HOST); } } } return httpUtils; }
/** * 添加公共参数拦截器 */ static class MyInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); HttpUrl httpUrl = request.url() .newBuilder() .addQueryParameter("source", "android") .build(); Request build = request.newBuilder() .url(httpUrl) .build(); return chain.proceed(build); } }
}
//5、创建回传类OnNetListener
public interface OnNetListener{ public void onSuccess(T t); public void onFailure(Exception e); }
//创建接口地址类
public class URL_API { public static final String BASE_URL = "https://www.zhaoapi.cn/"; public static final String LOGIN_URL = "user/login"; public static final String REGISTER_URL = "user/reg"; }
-----------------登录---------------
//创建LoginBean
public class LoginBean { private String msg; private String code; private DataBean data; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { private Object age; private String appkey; private String appsecret; private String createtime; private Object email; private Object fans; private Object follow; private Object gender; private Object icon; private Object latitude; private Object longitude; private String mobile; private Object money; private Object nickname; private String password; private Object praiseNum; private String token; private int uid; private Object userId; private String username; public Object getAge() { return age; } public void setAge(Object age) { this.age = age; } public String getAppkey() { return appkey; } public void setAppkey(String appkey) { this.appkey = appkey; } public String getAppsecret() { return appsecret; } public void setAppsecret(String appsecret) { this.appsecret = appsecret; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public Object getEmail() { return email; } public void setEmail(Object email) { this.email = email; } public Object getFans() { return fans; } public void setFans(Object fans) { this.fans = fans; } public Object getFollow() { return follow; } public void setFollow(Object follow) { this.follow = follow; } public Object getGender() { return gender; } public void setGender(Object gender) { this.gender = gender; } public Object getIcon() { return icon; } public void setIcon(Object icon) { this.icon = icon; } public Object getLatitude() { return latitude; } public void setLatitude(Object latitude) { this.latitude = latitude; } public Object getLongitude() { return longitude; } public void setLongitude(Object longitude) { this.longitude = longitude; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public Object getMoney() { return money; } public void setMoney(Object money) { this.money = money; } public Object getNickname() { return nickname; } public void setNickname(Object nickname) { this.nickname = nickname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Object getPraiseNum() { return praiseNum; } public void setPraiseNum(Object praiseNum) { this.praiseNum = praiseNum; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public Object getUserId() { return userId; } public void setUserId(Object userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } }
//创建ILoginModel
public interface ILoginModel { public void login(String mobile, String password, OnNetListeneronNetListener); }
//创建LoginModel
public class LoginModel implements ILoginModel { @Override public void login(String mobile, String password, final OnNetListeneronNetListener) { ServiceApi serviceApi = RetrofitHelper.getApi(); serviceApi.login(mobile, password) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer () { @Override public void accept(LoginBean loginBean) throws Exception { onNetListener.onSuccess(loginBean); } }, new Consumer () { @Override public void accept(Throwable throwable) throws Exception { onNetListener.onFailure(throwable); } }); } }
//创建LgoinPresenter
public class LoginPresenter { private final ILoginModel iLoginModel; private ILoginView iLoginView; public LoginPresenter(ILoginView iLoginView) { this.iLoginView = iLoginView; iLoginModel = new LoginModel(); } public void login() { String mobile = iLoginView.getMobile(); String password = iLoginView.getPassword(); iLoginModel.login(mobile, password, new OnNetListener() { @Override public void onSuccess(LoginBean loginBean) { iLoginView.suceess(loginBean.getMsg()); if (loginBean.getCode().equals("0")) { iLoginView.show(loginBean); iLoginView.toRegisterAc(); iLoginView.toMainAc(); } } @Override public void onFailure(Throwable throwable) { iLoginView.failure(throwable.getMessage()); } }); } public void toRegister() { iLoginView.toRegisterAc(); } }
//创建ILoginView
public interface ILoginView {
public String getMobile(); public String getPassword(); public void suceess(String string); public void failure(String string); public void toRegisterAc(); public void toMainAc(); public void show(LoginBean loginBean);
}
//创建LoginActivity
public class LoginActivity extends AppCompatActivity implements ILoginView, View.OnClickListener { /** * 请输入手机号 */ private EditText mEtMobile; /** * 请输入密码 */ private EditText mEtPassword; /** * 登录 */ private Button mBtLogin; /** * 新用户注册 */ private TextView mTvRegister; private LoginPresenter loginPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initView(); loginPresenter = new LoginPresenter(this); } @Override public void onClick(View v) { switch (v.getId()) { default: break; case R.id.bt_login: loginPresenter.login(); break; case R.id.tv_register:
loginPresenter.toRegister();
break; } } private void initView() { mEtMobile = (EditText) findViewById(R.id.et_mobile); mEtPassword = (EditText) findViewById(R.id.et_password); mBtLogin = (Button) findViewById(R.id.bt_login); mBtLogin.setOnClickListener(this); mTvRegister = (TextView) findViewById(R.id.tv_register); mTvRegister.setOnClickListener(this); }
@Override public String getMobile() { return mEtPassword.getText().toString().trim(); } @Override public String getPassword() { return mEtPassword.getText().toString().trim(); } @Override public void suceess(String string) { Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show(); } @Override public void failure(String string) { Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show(); } @Override public void toRegisterAc() { Intent intent = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(intent); } @Override public void toMainAc() { Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); } @Override public void show(LoginBean loginBean) { if (loginBean.getCode().equals("0")) { int uid = loginBean.getData().getUid(); MyApp.edit.putInt("uid", uid); MyApp.edit.commit(); } }
}//LoginActivity的XML布局
xml version="1.0" encoding="utf-8"?> <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="com.hh.newproject.view.LoginActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/leftjiantou" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="20sp" android:text="登录" /> RelativeLayout> <EditText android:id="@+id/et_mobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入手机号" /> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入密码" android:password="true" /> <Button android:id="@+id/bt_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:text="登录" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="忘记密码" /> <TextView android:id="@+id/tv_register" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="新用户注册" /> RelativeLayout> LinearLayout>
------------------------注册----------------------
//RegisterBean
public class RegisterBean { /** * msg : 注册成功 * code : 0 */ private String msg; private String code; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
//创建IRegisterModel
public interface IRegisterModel { public void register(String mobile, String password, OnNetListeneronNetListener); }
//创建RegisterModel
public class RegisterModel implements IRegisterModel { @Override public void register(String mobile, String password, final OnNetListeneronNetListener) { ServiceApi serviceApi = RetrofitHelper.getApi(); serviceApi.register(mobile, password) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer () { @Override public void accept(RegisterBean registerBean) throws Exception { onNetListener.onSuccess(registerBean); } }, new Consumer () { @Override public void accept(Throwable throwable) throws Exception { onNetListener.onFailure(throwable); } }); } }
//创建RegisterPresenter
public class RegisterPresenter { private IRegisterView iRegisterView; private final IRegisterModel iRegisterModel; public RegisterPresenter(IRegisterView iRegisterView) { this.iRegisterView = iRegisterView; iRegisterModel = new RegisterModel(); } public void register() { String mobile = iRegisterView.getMobile(); String password = iRegisterView.getPassword(); iRegisterModel.register(mobile, password, new OnNetListener() { @Override public void onSuccess(RegisterBean registerBean) { iRegisterView.suceess(registerBean.getMsg()); if (registerBean.getCode().equals("0")) { iRegisterView.toLoginAc(); } } @Override public void onFailure(Throwable throwable) { iRegisterView.failure(throwable.getMessage()); } }); } }
//创建IRegisterView
public interface IRegisterView {
public String getMobile(); public String getPassword(); public void suceess(String string); public void failure(String string); public void toLoginAc();
}//创建RegisterActivity
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener, IRegisterView { /** * 请输入手机号 */ private EditText mEtMobile; /** * 请输入密码 */ private EditText mEtPassword; /** * 注册 */ private Button mBtRegister; private ImageView mIvBack; private RegisterPresenter registerPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); initView(); registerPresenter = new RegisterPresenter(this); } private void initView() { mEtMobile = (EditText) findViewById(R.id.et_mobile); mEtPassword = (EditText) findViewById(R.id.et_password); mBtRegister = (Button) findViewById(R.id.bt_register); mBtRegister.setOnClickListener(this); mIvBack = (ImageView) findViewById(R.id.iv_back); mIvBack.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { default: break; case R.id.bt_register: registerPresenter.register(); break; case R.id.iv_back: finish(); break; } } @Override public String getMobile() { return mEtMobile.getText().toString().trim(); } @Override public String getPassword() { return mEtPassword.getText().toString().trim(); } @Override public void Success(String str) { Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(); } @Override public void failure(String str) { Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(); }
@Override public void toLoginAc() { Intent intent = new Intent(RegisterActivity.this, LoginActivity.class); startActivity(intent); }
}//RegisterActivity的XML布局
<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="com.hh.newproject.view.RegisterActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/iv_back" android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/leftjiantou" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="注册" android:textSize="20sp" /> RelativeLayout> <EditText android:id="@+id/et_mobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入手机号" /> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入密码" android:password="true" /> <Button android:id="@+id/bt_register" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:text="注册" /> LinearLayout>