然而我们在用 基础版mvp
开发的时候, 会遇到这样一些问题:
一般来讲, Activity会持有Presenter的引用, Presenter也会持有Activity的引用, 这就导致了一个问题, 当Activity退出销毁后, 由于 P层仍持有Activity的引用, 导致Activity无法释放, 最终会引起内存泄漏!
怎么办呢? 网上也有许多解决方法, 把这个Activity用弱引用包裹一下 :
public abstract class BasePresenter<V extends IView> {
/**弱引用, 防止内存泄漏*/
private WeakReference<V> weakReference;
/**
* 关联V层和P层
*/
public void attatchView(V v) {
weakReference = new WeakReference<>(v);
}
/**
* @return P层和V层是否关联.
*/
public boolean isViewAttached() {
return weakReference != null && weakReference.get() != null;
}
/**
* 断开V层和P层
* 在Acitivity的onDestory()中调用
*/
public void detachView() {
if (isViewAttached()) {
weakReference.clear();
weakReference = null;
}
}
...
}
问题二
当P层的逻辑处理完后, 我们就要调用V层来处理UI了, 怎么拿到V层的引用呢? 很简单, 定义一个方法:
public V getView() {
return isViewAttached() ? weakReference.get() : null;
}
但是这个方法有个很让人不安的返回值, 它有可能返回null. 试想一下, 用户打开了一个页面(Activity), 这个页面的P层去网络请求, 也许网络比较卡, 用户没等结果返回, 就退出了该页面.此时网络请求仍在继续.直到好不容易有结果返回的时候, P层调用getView()方法去更新ui, activity弱引用已经释放掉了, getView()就会返回null, 就会发生喜闻乐见的空指针异常!
怎么办? 办法也很简单, 在getView()方法调用的时候, 加一层判断:
if(isViewAttached()){
getView().xxxx
}
但是,在每一次调用 getView().xxx 时都要判断一下就很麻烦,这个时候 java的动态代理就可以在每次调用 getView().xxx 前都进行一下判断.
最好在BasePresenter类中都处理好了, 调用起来没有后顾之忧就爽多了.
在attatchView()的时候, 生成Activity的代理类, 在每个Activity方法被调用之前判空下 Activity, 如果Activity存在, 就让这个代理类执行更新ui的方法, 如果被销毁了, 就啥都不做. 废话不多说, show code:
public interface IView {
}
======================== Presenter层 ===================================
public abstract class BasePresenter<V extends IView> {
/**弱引用, 防止内存泄漏*/
private WeakReference<V> weakReference;
private V mProxyView;
/**
* 关联V层和P层
*/
public void attatchView(V v) {
weakReference = new WeakReference<>(v);
MvpViewHandler viewHandler = new MvpViewHandler(weakReference.get());
mProxyView = (V) Proxy.newProxyInstance(v.getClass().getClassLoader(), v.getClass().getInterfaces(), viewHandler);
}
/**
* @return P层和V层是否关联.
*/
public boolean isViewAttached() {
return weakReference != null && weakReference.get() != null;
}
/**
* 断开V层和P层
*/
public void detachView() {
if (isViewAttached()) {
weakReference.clear();
weakReference = null;
}
}
public V getView() {
return mProxyView;
}
private class MvpViewHandler implements InvocationHandler {
private IView mvpView;
MvpViewHandler(IView mvpView) {
this.mvpView = mvpView;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//如果V层没被销毁, 执行V层的方法.
if (isViewAttached()) {
return method.invoke(mvpView, args);
}
//P层不需要关注V层的返回值
return null;
}
}
}
======================== View层 ===================================
public abstract class BaseActivity<V extends BasePresenter> extends Activity implements IView{
V mPresenter;
@NonNull
protected abstract V newPresenter();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPresenter=newPresenter();
mPresenter.attatchView(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
mPresenter.detachView();
}
}
封装以后,以后就可以这样用了
/**
* 功能:View和Presenter 的协议
*/
public interface Contract {
interface View extends IView{
void updateText(String str);
}
interface Presenter {
void changeText();
}
}
======================== View层 ===================================
public class MyActivity extends BaseActivity<MyActivityPresenter> implements Contract.View {
TextView textView;
Button btn;
@NonNull
@Override
protected MyActivityPresenter newPresenter() {
return new MyActivityPresenter();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
textView=findViewById(R.id.tv);
btn=findViewById(R.id.btnChangeTv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPresenter.changeText();
}
});
}
@Override
public void updateText(String str) {
textView.setText(str);
}
}
======================== Presenter层 ===================================
public class MyActivityPresenter extends BasePresenter<Contract.View> implements Contract.Presenter {
@Override
public void changeText() {
String newText=Model.getNewString();
//动态代理自动帮我们 判断 mView是否为null
getView().updateText(newText);
}
}
======================== Model层 ===================================
/**
* 功能:Model层提供数据
*/
public class Model {
public static String getNewString(){
return "New String...";
}
}
还有另外的代理方式 ,学习成本很高(难看懂)
引入视图动态代理+一级缓存的MVP
public abstract class AbstractViewCacheProxy<T extends IView> implements InvocationHandler {
/* 如果是weakhashmap。Fragment destroy view就会回收数据了 */
private final Map<Method, Object[]> mViewCaches = new HashMap<>();
private WeakReference<T> mView;
public T proxy(Class<T> viewClass) {
if (viewClass == null) {
throw new NullPointerException("Proxy class is NULL, vmProxy is NULL!");
}
return (T) Proxy.newProxyInstance(viewClass.getClassLoader(), new Class[]{viewClass}, this);
}
void bind(T view) {
if (view == null) {
return;
}
unBind();
mView = new WeakReference<>(view);
for (Method method : mViewCaches.keySet()) {
invokeMethod(view, method, mViewCaches.get(method));
LogHelperUtil.i("AbstractViewCacheProxy-bind: ", method.getName());
}
view.bindProxyFinish();
}
void unBind() {
if (mView != null) {
mView.clear();
mView = null;
}
}
boolean isBind() {
return mView != null && mView.get() != null;
}
void destroy() {
unBind();
mViewCaches.clear();
onDestroy();
}
/* 请在此处释放和清理资源 */
protected abstract void onDestroy();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (isCacheMethod(method)) {
mViewCaches.put(method, args);
}
if (mView != null && mView.get() != null) {
return invokeMethod(mView.get(), method, args);
}
return null;
}
private boolean isCacheMethod(Method method) {
CacheMethod cacheMethod = method.getAnnotation(CacheMethod.class);
return cacheMethod != null && cacheMethod.isCached();
}
private Object invokeMethod(Object view, Method method, Object[] args) {
if (view == null || method == null) {
return null;
}
try {
return method.invoke(view, args);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
来自 : 浅谈Android中的MVP与动态代理