MVP 使用文档
导入
将MVP资源包导入
在settings.gradle设置如下目录
rootProject.name='Test'
include ':app'
include ': mvplib '
include ' : mvplib:libMvpAnotation:compiler '
在 app build.gradle
implementation project(path: ':mvplib')
annotationProcessor project(path: ':mvplib:libMvpAnotation:compiler')
注释: compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
必须使用java8依赖
必须导入version.gradlee
使用
注释使用
@MvpEntity
使用该注解得到从服务器beam类(这里要特别注意code值)
@MvpEntity
public class HttpResult<T> implements IMvpEntity<T> {
/**
* 'code': '1',
* 'message': '成功提示',
* 'data':
*/
private int code;
private String message;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public boolean isOk() {
//每个服务器返回的code值
return code == 1 && data != null;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
@OkInterceptor(1)
添加自定义ok拦截器
@OkInterceptor(1)//括号里代表OK连接器的等级
public class Intercepter1 implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
return chain.proceed(chain.request());
}
}
@ApiService
自定义ApiService
@ApiService
public interface AppApiService {
@POST()
Observable<HttpResult<User>> getUser(@FieldMap HashMap<String, Object> map);
}
@BaseUrl
自定义BaseUrl
public interface Constrant {
@BaseUrl
String BASE_URL = "https://www.seetao.com";
}
设置请求params
public class MvpApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
MvpManager.setParamsGetter(ParamsUtils::getCommonParams);
}
}
自定义解析GsonFactory
@GsonConverter
public class JDGsonConverterFactory extends MvpGsonConverterFactory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new JDGsonResponseBodyConverter<>(gson, adapter,type);
}
}
/**
* 继承BaseSmartFragment1<>范型返回需要的解析的数据
*/
public class JDGsonResponseBodyConverter<T> extends MvpGsonResponseBodyConverter<T> {
public JDGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter, Type type) {
super(gson, adapter, type);
}
@Override
public String handJson(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
if(!jsonObject.isNull("code")){
int code = jsonObject.getInt("code");
if(code != 1){ // 失败
if(!jsonObject.isNull("data")){
String data = jsonObject.getString("data");
if(TextUtils.isEmpty(data)){ // 如果 data 是一个空字符串
jsonObject.remove("data");
return jsonObject.toString();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
}
使用
ONE 继承BaseSmartFragment1
使用在Fragment页面
public class VideoFragment extends BaseSmartFragment1<VideoBean> {
/**
*
* @return
* 返回该类所在xml布局
*/
@Override
protected int getLayoutId() {
return R.layout.fragment_video;
}
/**
*
* @param data
* 接受成功bean类
*/
@Override
public void onResult1(MvpResponse<VideoBean> data) {
if (data.getCode() == 1) {
Toast.makeText(getActivity(), data.getData().getList().get(1).getShare_link(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), data.getMsg(), Toast.LENGTH_SHORT).show();
}
}
/**
* 1.创建请求对象如果是
* 范型中添加得到bean类
* Get请求创建GetRequest
* Post请求创建PostRequest
* 2.如果有参数调用
* request.setParams();设置参数
*3.调用请求方法
* doRequest(request);
*/
@Override
protected void initView() {
super.initView();
GetRequest<VideoBean> request = new GetRequest<>("/app/v_1_6/article/videolist");
doRequest(request);
}
/**
*
* @param view
* 绑定View
*/
@Override
protected void bindView(View view) {
super.bindView(view);
}
TWO(在p层处理逻辑)
重写p层
创建契约类
创建Presenter继承IBasePresenter
创建View继承IBaseView
public interface ConstrantVideo {
// 创建P层继承IBasePresenter
interface IVideoPresenter extends IBasePresenter<IVideoView> {
//p传递数据方法
void getVideoData();
}
// 创建View契约类
interface IVideoView extends IBaseView<ConstrantVideo.IVideoPresenter> {
void onSucces(Video video);
void onFail(String error);
void onNetError();
void showLoadLing();
void closeLoadLing();
}
}
创建P层
BaseRepository创建model成员变量在P层构造方法通过new BaseRepository()得到model实例
在P层方法中根据请求Url 创建GetRequest或者PostRequest对象
如果有参数设置请求参数
通过model对象调用mModel.doRequest(request,new IBaseCallBack<T>{})获得数据
public class VideoPresenter extends BasePresenter<ConstrantVideo.IVideoView> implements ConstrantVideo.IVideoPresenter {
private BaseRepository mModel;
private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
public VideoPresenter() {
mModel = new BaseRepository();
}
@Override
public void getVideoData() {
// 给请求对象添加参数
GetRequest request = new GetRequest("/app/v_1_6/article/videolist");
// 设置请求参数
request.setParams(ParamsUtils.getCommonParams());
request.setType(Video.class);
// 加载动画
mView.showLoadLing();
mModel.doRequest(request, new IBaseCallBack<Video>() {
// 切断cut方法
@Override
public void onCut(Disposable disposable) {
mCompositeDisposable.add(disposable);
}
// 获取结果
@Override
public void onResult(MvpResponse<Video> data) {
if (data.getCode() == 1) {
mView.onSucces(data.getData());
mView.closeLoadLing();
} else {
mView.onFail(data.getMsg());
}
}
});
}
@Override
public boolean cancelRequest() {
return true;
}
}
Fragmenrt
继承BaseMvpFragment<T extend IBasePresenter>implements具体的View
在成功失败方法得到数据
public class VideoFragmenrt extends BaseMvpFragment<ConstrantVideo.IVideoPresenter> implements ConstrantVideo.IVideoView {
@Override
protected int getLayoutView() {
return R.layout.fragment_video_fragmenrt;
}
@Override
public void onSucces(Video video) {
toast(video.getList().get(2).getShare_link());
}
@Override
public void onFail(String error) {
toast(error);
}
@Override
public void onNetError() {
toast("网络错误");
}
@Override
public void showLoadLing() {
showPopLoading();
}
@Override
public void closeLoadLing() {
closeLoading();
}
@Override
public ConstrantVideo.IVideoPresenter creatPresenter() {
return new VideoPresenter();
}
@Override
protected void initView() {
mPresenter.getVideoData();
}
}
Three(在model层做数据缓存)
重写model层
在Fragment
//重写createPresenter 返回自定义的model 层
@Override
public BaseSmartPresenter1<RecommendData, ?> createPresenter() {
return new BaseSmartPresenter1<>(RecommondRepository.getInstance());
}
重写model
public class RecommondRepository extends BaseRepository {
private static final String CACHE_FILE_NAME_PREFIX = "version_code";
private static RecommondRepository mInstance;
private HashMap<String, RecommendData> mMemoryData = new HashMap<>();
/**
*
* @return
* 单例是的只有一个model对象
*/
public static RecommondRepository getInstance() {
// 判断对象是否创建
if (mInstance == null) {
// 在此处创建线程索让其他线程减少等待时间
synchronized (RecommondRepository.class) {
// 如果线程1拿到锁对象未创建完成,线程2拿到锁创建完对象线程1继续创建此时对象已经通过线程2实例化所以进行二次判空
if (mInstance == null) {
// 创建对象
mInstance = new RecommondRepository();
}
}
}
return mInstance;
}
@Override
public <T> void doRequest(LifecycleProvider lifecycleProvider, MvpRequest<T> request, IBaseCallBack<T> callBack) {
/*取数据*/
// 不调用父类的方法,重写子类
// super.doRequest(lifecycleProvider, request, callBack);
// 得到栏目ID
String columnId = request.getParams().get(Constract.RequestKey.KEY_COLUMN_ID).toString();
switch (request.getRequestType()) {
// case加入括号{}可以重复创建变量局部变量只能在方法里有效
/**
* 默认都是第一次请求
* 刷新和加载更多都不需要读取缓存数据
*/
case FIRST: {
// step1.先从内从存查找直接传入P层
MvpResponse response = getFromMemory(columnId);
if (response != null) {
callBack.onResult(response);
return;
}
// step2.如果内存没有直接从sdcard读取
/*
*Observable 内置线程池节省系统开销
* scared都为耗时操作为 */
Observable.create(new ObservableOnSubscribe<MvpResponse>() {
@Override
public void subscribe(@NonNull ObservableEmitter<MvpResponse> emitter) throws Throwable {
MvpResponse fromSdCard = getFromSdCard(columnId);
if (fromSdCard != null) {
emitter.onNext(fromSdCard);
emitter.onComplete();
} else {
emitter.onError(new NullPointerException("sdcard no data"));
}
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<MvpResponse>() {
@Override
public void accept(MvpResponse mvpResponse) throws Throwable {
callBack.onResult(mvpResponse);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Throwable {
doRequest(lifecycleProvider, request, callBack, new CacheTask<>(request));
}
});
break;
}
default:{
// 从服务请求
doRequest(lifecycleProvider,request,callBack,new CacheTask<>(request));
}
}
}
// 读取内存数据
private MvpResponse getFromMemory(String key) {
// 看内存是否有该数据
RecommendData data = mMemoryData.get(key);
if (data != null) {
// 设置数据
MvpResponse<RecommendData> response = new MvpResponse<>();
return response.setData(data).setCode(1).setRequestType(RequestType.FIRST).setType(ResponseType.MEMORY);
}
return null;
}
/**
* @param key
* @return 从sd卡读取文件
*/
private MvpResponse getFromSdCard(String key) {
// 从内存卡读取数据
RecommendData data = MvpDataFileCacheUtils.getencryptedDataFromFile(getCacheDataSdcardFile(key), RecommendData.class);
if (data != null) {
MvpResponse<RecommendData> response = new MvpResponse<>();
return response.setCode(1).setData(data).setType(ResponseType.SDCARD);
}
return null;
}
/**
* @param columnId
* @return 创建手机文件
*/
// 找到文件
private File getCacheDataSdcardFile(String columnId) {
return new File(MvpManager.getExternalCacheDir(), CACHE_FILE_NAME_PREFIX + columnId);
}
// 缓存数据
private class CacheTask<T> implements Consumer<MvpResponse<T>> {//实现做缓存接口
private MvpRequest request;
CacheTask(MvpRequest request) {
this.request = request;
}
@SuppressWarnings("ALL")
@Override
public void accept(MvpResponse<T> mvpResponse) throws Throwable {
// 得到保存的Key值
String key = request.getParams().get(Constract.RequestKey.KEY_COLUMN_ID).toString();
saveToMemory((MvpResponse<RecommendData>) mvpResponse, request.getRequestType(), key);
saveToSdcard((MvpResponse<RecommendData>) mvpResponse, key);
}
// 保存到card
private void saveToSdcard(MvpResponse<RecommendData> mvpResponse, String key) {
}
// 保存到内存
private void saveToMemory(MvpResponse<RecommendData> mvpResponse, RequestType requestType, String key) {
if (requestType != RequestType.LOAD_MORE){//不是加载更多
mMemoryData.clear();//将内存设置空
RecommendData recommendData = new RecommendData();//创建空对象开辟内存
RecommendData serverData = mvpResponse.getData();//从网络获取data
// 设置数据
recommendData.setAlbumId(serverData.getAlbumId());
recommendData.setAlbumNews(serverData.getAlbumNews());
recommendData.setAlbumTitle(serverData.getAlbumTitle());
recommendData.setBannerList(serverData.getBannerList());
recommendData.setFlashId(serverData.getFlashId());
recommendData.setFlashNews(serverData.getFlashNews());
recommendData.setMore(serverData.getMore());
recommendData.setPointTime(serverData.getPointTime());
recommendData.setStart(serverData.getStart());
recommendData.setNews(new ArrayList<>(serverData.getNews()));
// 缓存到集合
mMemoryData.put(key,recommendData);
}else {
RecommendData cacheData = mMemoryData.get(key);//获取缓存加入数据
RecommendData serverData = mvpResponse.getData();//获取网络数据
// 如果网络数据和缓存数据都不为空
if(cacheData != null && serverData != null){
// 所有数据只有新闻数据需要实施gen新
cacheData.setStart(serverData.getStart());
cacheData.setNumber(serverData.getNumber());
cacheData.setPointTime(serverData.getPointTime());
cacheData.setMore(serverData.getMore());
cacheData.getNews().addAll(serverData.getNews());
}
}
}
}
}
网友评论