根据网上的资料进行自己手动搭建的一套网络请求框架,也为以后的使用做一个记录,废话不多,开始搭建!
1.首先我们先将依赖注入:
//网络请求
compile 'com.squareup.okhttp3:okhttp:3.9.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
//ConverterFactory的Gson依赖包
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
//CallAdapterFactory的Rx依赖包
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.2'
//这个是用来打log日志的,会比较清晰
implementation 'com.orhanobut:logger:2.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.9.1'
2.在AndroidManifest中加入网络请求的权限:(https的网络请求需要添加其他的东西,请自行上网查找)
3.首先编写存放父地址的类:(不好意思,时间久了,我都不知道我这api哪来的了··感谢开源)
public class BaseContent {
public static final String baseUrl = "http://www.energy-link.com.cn/";
//成功的返回码
public static final int SUCCESSCODE = 1;
}
4.编写请求参数类:(这里添加几种不同的请求方式:) : ApiServer接口类
//这个的请求方式是将参数拼接在问好后面(api/Activity/get_activities?time=“***”)
@GET("api/Activity/get_activities?")
Observable>> getMain(@Query("time") String requestType);
//这个的请求方式是将参数也拼接在后面,但是规则不一样(data/Android/count/10/page/1)
Observable>> getArticleData(@Path("count") int
count,@Path("page") int page)
//post请求,将参数放在body体中请求
@POST("work/getWork")
Observable>> getReservrList(@Body Map
params);
5.编写父Bean类:
public class BaseModel implements Serializable {
private String msg;
private int code;
private T data;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
6.编写子bean类:(因为就先试了一个接口,就只编写一个bean类)
public class MainBean {
/**
* id : 11
* act_logo : http://www.energy-link.com.cn/upload/admin/20180828/s_29a692567d0f0d84d515eb5cf5be98d0.jpg
* play_time : 2018-06-10
* name : 中国生物质能源产业联盟会员代表大会
* province : 北京市
* city : 西城区
*/
private int id;
private String act_logo;
private String play_time;
private String name;
private String province;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAct_logo() {
return act_logo;
}
public void setAct_logo(String act_logo) {
this.act_logo = act_logo;
}
public String getPlay_time() {
return play_time;
}
public void setPlay_time(String play_time) {
this.play_time = play_time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
7.编写ApiRetrofit类,用来实例化这个ApiServer接口类:
public class ApiRetrofit {
private static ApiRetrofit apiRetrofit;
private final Retrofit retrofit;
private ApiServer apiServer;
private String TAG = "ApiRetrofit %s";
//设置所有的超时时间
private static final int DEFAULT_TIMEOUT = 15;
//创建日志拦截器
public ApiRetrofit() {
OkHttpClient.Builder OkHttpClientBuilder = new OkHttpClient.Builder();
OkHttpClientBuilder
//创建的日志拦截器
.addInterceptor(interceptor)
.addInterceptor(getHttpInterceptor())
//设置连接超时时间
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
//设置写入文件的超时时间
.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
//设置读取文件的超时时间
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
//错误重连
.retryOnConnectionFailure(true);
retrofit = new Retrofit.Builder()
.baseUrl(BaseContent.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(OkHttpClientBuilder.build())
.build();
apiServer = retrofit.create(ApiServer.class);
}
private HttpLoggingInterceptor getHttpInterceptor() {
//日志显示级别
HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
//新建log拦截器
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("zcb", "OkHttp====Message:" + message);
}
});
loggingInterceptor.setLevel(level);
return loggingInterceptor;
}
//单例模式
public static ApiRetrofit getInstance() {
if (apiRetrofit == null) {
synchronized (Object.class) {
if (apiRetrofit == null) {
apiRetrofit = new ApiRetrofit();
}
}
}
return apiRetrofit;
}
public ApiServer getApiService() {
return apiServer;
}
public Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.currentTimeMillis();
Response proceed = chain.proceed(request);
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
MediaType mediaType = proceed.body().contentType();
String content = proceed.body().string();
Logger.wtf(TAG, "----------Request Start----------------");
printParams(request.body());
Logger.e(TAG, "| " + request.toString() + "===========" + request.headers().toString());
Logger.json(content);
Logger.e(content);
Logger.wtf(TAG, "----------Request End:" + duration + "毫秒----------");
return proceed.newBuilder()
.body(ResponseBody.create(mediaType, content))
.build();
}
};
private void printParams(RequestBody body) {
if (body != null) {
Buffer buffer = new Buffer();
try {
body.writeTo(buffer);
Charset charset = Charset.forName("UTF-8");
MediaType mediaType = body.contentType();
if (mediaType != null) {
charset = mediaType.charset(charset);
}
String params = buffer.readString(charset);
Logger.e(TAG, "请求参数: | " + params);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
8.在创建BaseObserver类,用来管理请求成功和失败之后的处理:(里面成功的code值一定要和自己的服务器对应上,我这里默认写的是1,还有错误的code值,都要根据你自己的项目决定)
public abstract class BaseObserver extends DisposableObserver {
private BaseView baseView;
/**
* 于服务器约定 返回code为几是正常请求
*/
public static final int CODE = BaseContent.SUCCESSCODE;
protected BaseView view;
/**
* 网络连接失败 无网
*/
public static final int NETWORK_ERROR = 100000;
/**
* 解析数据失败
*/
public static final int PARSE_ERROR = 1008;
/**
* 网络问题
*/
public static final int BAD_NETWORK = 1007;
/**
* 连接错误
*/
public static final int CONNECT_ERROR = 1006;
/**
* 连接超时
*/
public static final int CONNECT_TIMEOUT = 1005;
//错误的返回值
private int code;
public BaseObserver(BaseView view) {
this.baseView = view;
}
@Override
protected void onStart() {
super.onStart();
if (baseView != null) {
baseView.showLoading();
}
}
@Override
public void onComplete() {
}
@Override
public void onNext(T t) {
try {
if (baseView != null) {
baseView.hideLoading();
}
BaseModel baseModel = (BaseModel) t;
if (baseModel.getCode() == CODE) {
onSuccess(t);
} else {
if (baseView != null) {
baseView.showErrorCode(baseModel);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
try {
if (baseView != null) {
baseView.hideLoading();
} else if (e instanceof HttpException) {
//Http错误
onException(BAD_NETWORK, "", getErrorCode(e));
} else if (e instanceof ConnectException || e instanceof UnknownHostException) {
//连接错误
onException(CONNECT_ERROR, "", getErrorCode(e));
} else if (e instanceof InterruptedIOException) {
//连接超时
onException(CONNECT_TIMEOUT, "", getErrorCode(e));
} else if (e instanceof JsonParseException
|| e instanceof JSONException
|| e instanceof ParseException) {
// 解析错误
onException(PARSE_ERROR, "", getErrorCode(e));
e.printStackTrace();
} else {
if (e != null) {
onError(e.toString(), getErrorCode(e));
} else {
onError("未知错误", getErrorCode(e));
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
private void onException(int badNetwork, String s, int errorCode) {
if (!NetWorkUtil.isAvailableByPing()) {
badNetwork = NETWORK_ERROR;
s = "网络不可用,请检查网络连接!";
errorCode = 100000;
}
onExceptions(badNetwork, s, errorCode);
}
public int getErrorCode(Throwable e) {
ResponseBody body = ((HttpException) e).response().errorBody();
try {
String json = body.string();
BaseModel baseModel = new Gson().fromJson(json, BaseModel.class);
code = baseModel.getCode();
} catch (IOException IOe) {
IOe.printStackTrace();
}
return code;
}
private void onExceptions(int unknownError, String message, int code) {
switch (unknownError) {
case CONNECT_ERROR:
onError("连接错误", code);
break;
case CONNECT_TIMEOUT:
onError("连接超时", code);
break;
case BAD_NETWORK:
onError("网络超时", code);
break;
case PARSE_ERROR:
onError("数据解析失败", code);
break;
//网络不可用
case NETWORK_ERROR:
onError("网络不可用,请检查网络连接!", code);
break;
default:
break;
}
}
public abstract void onSuccess(T o);
public abstract void onError(String msg, int code);
}
9.创建BasePresenter,用来创建观察者和被观察者:
public class BasePresenter {
public V view;
private CompositeDisposable compositeDisposable;
protected ApiServer apiServer = ApiRetrofit.getInstance().getApiService();
public BasePresenter(V view) {
this.view = view;
}
//解除绑定View
public void detachView() {
view = null;
removeDisposable();
}
//返回View
public V getView() {
return view;
}
//添加观察者和被观察者
public void addDisposable(Observable> observable, BaseObserver baseObserver) {
if (compositeDisposable == null) {
compositeDisposable = new CompositeDisposable();
}
compositeDisposable.add(observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(baseObserver));
}
//移除观察者
public void removeDisposable() {
if (compositeDisposable != null) {
compositeDisposable.dispose();
}
}
}
10.创建BaseView接口类,用来设置成功失败所需要展示的东西:
public interface BaseView {
//显示Dialog
void showLoading();
//隐藏Dialog
void hideLoading();
//显示错误信息
void showErrorMsg(String msg);
//显示错误码
void showErrorCode(BaseModel model);
}
11.在使用Logger的时候,我们要创建一个Application,用来初始化一下它:(记得在AndroidManifest中注册)
public class App extends Application {
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
// 在 Application 中初始化
mContext = this;
initLogger();
}
public static Context getContext() {
return mContext;
}
private void initLogger() {
FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
.showThreadInfo(false) // 是否显示线程信息 默认显示 上图Thread Infrom的位置
.methodCount(0) // 展示方法的行数 默认是2 上图Method的行数
.methodOffset(7) // 内部方法调用向上偏移的行数 默认是0
// .logStrategy(customLog) // 改变log打印的策略一种是写本地,一种是logcat显示 默认是后者(当然也可以自己定义)
.tag("My custom tag") // 自定义全局tag 默认:PRETTY_LOGGER
.build();
Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
@Override
public boolean isLoggable(int priority, String tag) {
return true;
}
});
}
}
12.创建BaseActivity,将主要功能放在Base中,避免很多繁琐的步骤:
public abstract class BaseActivity extends AppCompatActivity implements BaseView{
private Context mContext;
protected T presenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(getLayoutId());
presenter = createPresenter();
init();
}
protected abstract void init();
//获取布局ID
protected abstract int getLayoutId();
//初始化P层
protected abstract T createPresenter();
@Override
public void showLoading() {
}
@Override
public void hideLoading() {
}
@Override
public void showErrorMsg(String msg) {
}
@Override
public void showErrorCode(BaseModel model) {
}
}
13.这是从网上找的网络请求判断工具类··(NetWorkUtil,很全)
public class NetWorkUtil {
private NetWorkUtil() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
public enum NetworkType {
NETWORK_WIFI,
NETWORK_4G,
NETWORK_3G,
NETWORK_2G,
NETWORK_UNKNOWN,
NETWORK_NO
}
/**
* 打开网络设置界面
* 3.0以下打开设置界面
*/
public static void openWirelessSettings() {
if (android.os.Build.VERSION.SDK_INT > 10) {
App.getContext().startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} else {
App.getContext().startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
/**
* 获取活动网络信息
* 需添加权限 {@code }
*
* @return NetworkInfo
*/
private static NetworkInfo getActiveNetworkInfo() {
ConnectivityManager cm = (ConnectivityManager) App.getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo();
}
/**
* 判断网络是否连接
* 需添加权限 {@code }
*
* @return {@code true}: 是
{@code false}: 否
*/
public static boolean isConnected() {
NetworkInfo info = getActiveNetworkInfo();
return info != null && info.isConnected();
}
/**
* 判断网络是否可用
* 需添加权限 {@code }
*
* @return {@code true}: 可用
{@code false}: 不可用
*/
public static boolean isAvailableByPing() {
CommandResult result = execCmd("ping -c 1 -w 1 223.5.5.5", false);
boolean ret = result.result == 0;
if (result.errorMsg != null) {
// isAvailableByPing errorMsg
Log.e("isAvailableByPing", result.errorMsg);
}
// isAvailableByPing successMsg
if (result.successMsg != null) {
Log.d("isAvailableByPing", result.successMsg);
}
return ret;
}
/**
* 判断移动数据是否打开
*
* @return {@code true}: 是
{@code false}: 否
*/
public static boolean getDataEnabled() {
try {
TelephonyManager tm = (TelephonyManager) App.getContext().getSystemService(Context.TELEPHONY_SERVICE);
Method getMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("getDataEnabled");
if (null != getMobileDataEnabledMethod) {
return (boolean) getMobileDataEnabledMethod.invoke(tm);
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 打开或关闭移动数据
* 需系统应用 需添加权限{@code }
*
* @param enabled {@code true}: 打开
{@code false}: 关闭
*/
public static void setDataEnabled(boolean enabled) {
try {
TelephonyManager tm = (TelephonyManager) App.getContext().getSystemService(Context.TELEPHONY_SERVICE);
Method setMobileDataEnabledMethod = tm.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
if (null != setMobileDataEnabledMethod) {
setMobileDataEnabledMethod.invoke(tm, enabled);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 判断网络是否是4G
* 需添加权限 {@code }
*
* @return {@code true}: 是
{@code false}: 否
*/
public static boolean is4G() {
NetworkInfo info = getActiveNetworkInfo();
return info != null && info.isAvailable() && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE;
}
/**
* 判断wifi是否打开
* 需添加权限 {@code }
*
* @return {@code true}: 是
{@code false}: 否
*/
public static boolean getWifiEnabled() {
WifiManager wifiManager = (WifiManager) App.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
return wifiManager.isWifiEnabled();
}
/**
* 打开或关闭wifi
* 需添加权限 {@code }
*
* @param enabled {@code true}: 打开
{@code false}: 关闭
*/
public static void setWifiEnabled(boolean enabled) {
WifiManager wifiManager = (WifiManager) App.getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (enabled) {
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
} else {
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
}
}
}
/**
* 判断wifi是否连接状态
* 需添加权限 {@code }
*
* @return {@code true}: 连接
{@code false}: 未连接
*/
public static boolean isWifiConnected() {
ConnectivityManager cm = (ConnectivityManager) App.getContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm != null && cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
}
/**
* 判断wifi数据是否可用
* 需添加权限 {@code }
* 需添加权限 {@code }
*
* @return {@code true}: 是
{@code false}: 否
*/
public static boolean isWifiAvailable() {
return getWifiEnabled() && isAvailableByPing();
}
/**
* 获取网络运营商名称
* 中国移动、如中国联通、中国电信
*
* @return 运营商名称
*/
public static String getNetworkOperatorName() {
TelephonyManager tm = (TelephonyManager) App.getContext().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null ? tm.getNetworkOperatorName() : null;
}
private static final int NETWORK_TYPE_GSM = 16;
private static final int NETWORK_TYPE_TD_SCDMA = 17;
private static final int NETWORK_TYPE_IWLAN = 18;
/**
* 获取当前网络类型
* 需添加权限 {@code }
*
* @return 网络类型
*
* - {@link NetworkType#NETWORK_WIFI }
* - {@link NetworkType#NETWORK_4G }
* - {@link NetworkType#NETWORK_3G }
* - {@link NetworkType#NETWORK_2G }
* - {@link NetworkType#NETWORK_UNKNOWN}
* - {@link NetworkType#NETWORK_NO }
*
*/
public static NetworkType getNetworkType() {
NetworkType netType = NetworkType.NETWORK_NO;
NetworkInfo info = getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
netType = NetworkType.NETWORK_WIFI;
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
switch (info.getSubtype()) {
case NETWORK_TYPE_GSM:
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
netType = NetworkType.NETWORK_2G;
break;
case NETWORK_TYPE_TD_SCDMA:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
netType = NetworkType.NETWORK_3G;
break;
case NETWORK_TYPE_IWLAN:
case TelephonyManager.NETWORK_TYPE_LTE:
netType = NetworkType.NETWORK_4G;
break;
default:
String subtypeName = info.getSubtypeName();
if (subtypeName.equalsIgnoreCase("TD-SCDMA")
|| subtypeName.equalsIgnoreCase("WCDMA")
|| subtypeName.equalsIgnoreCase("CDMA2000")) {
netType = NetworkType.NETWORK_3G;
} else {
netType = NetworkType.NETWORK_UNKNOWN;
}
break;
}
} else {
netType = NetworkType.NETWORK_UNKNOWN;
}
}
return netType;
}
/**
* 获取IP地址
* 需添加权限 {@code }
*
* @param useIPv4 是否用IPv4
* @return IP地址
*/
public static String getIPAddress(boolean useIPv4) {
try {
for (Enumeration nis = NetworkInterface.getNetworkInterfaces(); nis.hasMoreElements(); ) {
NetworkInterface ni = nis.nextElement();
// 防止小米手机返回10.0.2.15
if (!ni.isUp()) continue;
for (Enumeration addresses = ni.getInetAddresses(); addresses.hasMoreElements(); ) {
InetAddress inetAddress = addresses.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String hostAddress = inetAddress.getHostAddress();
boolean isIPv4 = hostAddress.indexOf(':') < 0;
if (useIPv4) {
if (isIPv4) return hostAddress;
} else {
if (!isIPv4) {
int index = hostAddress.indexOf('%');
return index < 0 ? hostAddress.toUpperCase() : hostAddress.substring(0, index).toUpperCase();
}
}
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取域名ip地址
* 需添加权限 {@code }
*
* @param domain 域名
* @return ip地址
*/
public static String getDomainAddress(final String domain) {
try {
ExecutorService exec = Executors.newCachedThreadPool();
Future fs = exec.submit(new Callable() {
@Override
public String call() throws Exception {
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(domain);
return inetAddress.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
});
return fs.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}
/**
* 是否是在root下执行命令
*
* @param command 命令
* @param isRoot 是否需要root权限执行
* @return CommandResult
*/
public static CommandResult execCmd(String command, boolean isRoot) {
return execCmd(new String[]{command}, isRoot, true);
}
/**
* 是否是在root下执行命令
*
* @param commands 命令数组
* @param isRoot 是否需要root权限执行
* @param isNeedResultMsg 是否需要结果消息
* @return CommandResult
*/
public static CommandResult execCmd(String[] commands, boolean isRoot, boolean isNeedResultMsg) {
int result = -1;
if (commands == null || commands.length == 0) {
return new CommandResult(result, null, null);
}
Process process = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = null;
StringBuilder errorMsg = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec(isRoot ? "su" : "sh");
os = new DataOutputStream(process.getOutputStream());
for (String command : commands) {
if (command == null) continue;
os.write(command.getBytes());
os.writeBytes("\n");
os.flush();
}
os.writeBytes("exit\n");
os.flush();
result = process.waitFor();
if (isNeedResultMsg) {
successMsg = new StringBuilder();
errorMsg = new StringBuilder();
successResult = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
String s;
while ((s = successResult.readLine()) != null) {
successMsg.append(s);
}
while ((s = errorResult.readLine()) != null) {
errorMsg.append(s);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeIO(os, successResult, errorResult);
if (process != null) {
process.destroy();
}
}
return new CommandResult(
result,
successMsg == null ? null : successMsg.toString(),
errorMsg == null ? null : errorMsg.toString()
);
}
/**
* 返回的命令结果
*/
public static class CommandResult {
/**
* 结果码
**/
public int result;
/**
* 成功信息
**/
public String successMsg;
/**
* 错误信息
**/
public String errorMsg;
public CommandResult(int result, String successMsg, String errorMsg) {
this.result = result;
this.successMsg = successMsg;
this.errorMsg = errorMsg;
}
}
/**
* 关闭IO
*
* @param closeables closeable
*/
public static void closeIO(Closeable... closeables) {
if (closeables == null) return;
for (Closeable closeable : closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
14.编写子类去实现P层和V层:(P层)
public class MainPresenter extends BasePresenter {
private final MainView childView;
public MainPresenter(MainView view) {
super(view);
childView = (MainView) view;
}
public void getNet() {
addDisposable(apiServer.getMain("year"), new BaseObserver(view) {
@Override
public void onSuccess(Object o) {
childView.onMainSuccess((BaseModel>) o);
}
@Override
public void onError(String msg, int code) {
childView.onMainError(msg, code);
}
});
}
}
15.子V层:
public interface MainView extends BaseView {
void onMainSuccess(BaseModel> bean);
void onMainError(String Msg,int code);
}
16.看下MainActivity是如何使用的:
public class MainActivity extends BaseActivity implements MainView {
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
protected void init() {
presenter.getNet();
}
@Override
protected MainPresenter createPresenter() {
return new MainPresenter(this);
}
@Override
public void onMainSuccess(BaseModel> bean) {
List data = bean.getData();
for (int i = 0; i < data.size(); i++) {
MainBean mainBean = data.get(i);
Log.e("----------", mainBean.getCity());
Log.e("----------", mainBean.getName());
}
}
@Override
public void onMainError(String Msg, int code) {
Log.e("----------", Msg + code);
}
@Override
protected void onDestroy() {
super.onDestroy();
presenter.detachView();
}
}