美文网首页
Volley与内存泄露

Volley与内存泄露

作者: Mr_villain | 来源:发表于2016-08-08 14:14 被阅读935次

    前言

    这几天突然很好奇volley的取消操作是如何实现的,就去看了下volley的源码,突然发现,volley的取消操作实现的很简单,很失望。然后突然想到另外一个很敏感的问题——内存泄露。

    正文

    首先来看下volley的源码吧

    Request.cancel() && Request.isCanceled()

    private boolean mCanceled;
    /** 
     * Mark this request as canceled.  No callback will be delivered. 
     */
    public void cancel() {    
        mCanceled = true;
    }
    /** 
     * Returns true if this request has been canceled. 
     */
    public boolean isCanceled() {    
        return mCanceled;
    }
    

    cancel的操作十分简单,就单纯地给mCanceled赋了个true值。

    NetworkDispatcher

    这个类在volley库中负责网络请求的运行,继承自Thread类。

    NetworkDispatcher.run()

    @Override
    public void run() {    
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);   
        Request<?> request;    
        while (true) {        
            long startTimeMs = SystemClock.elapsedRealtime();        
            // release previous request object to avoid leaking request object when mQueue is drained.
            request = null;       
            try {            
            // Take a request from the queue.            
                request = mQueue.take();        
                } catch (InterruptedException e) {            
                // We may have been interrupted because it was time to quit.            
                    if (mQuit) {                
                        return;           
                    }           
                    continue;        
                }        
                try {            
                    request.addMarker("network-queue-take");            
                    // If the request was cancelled already, do not perform the            
                    // network request.            
                    if (request.isCanceled()) {                
                        request.finish("network-discard-cancelled");                
                        continue;           
                    }            
                    addTrafficStatsTag(request);            
                    // Perform the network request.            
                    NetworkResponse networkResponse = mNetwork.performRequest(request);                                
                    request.addMarker("network-http-complete");            
                    // If the server returned 304 AND we delivered a response already,            
                    // we're done -- don't deliver a second identical response.            
                    if (networkResponse.notModified && request.hasHadResponseDelivered()) {                          
                        request.finish("not-modified");                
                        continue;            
                    }            
                    //  缓存使用,只有没有网络的情况下,如果是返回失败,如果网络请求返回数据失败,怎么办,不刷新            
                    // Parse the response here on the worker thread.            
                    Response<?> response = request.parseNetworkResponse(networkResponse);                    
                    request.addMarker("network-parse-complete");            
                    // Write to cache if applicable.            
                    // TODO: Only update cache metadata instead of entire record for 304s.            
                    if (networkResponse.statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE && request.shouldCache()) {                
                        Cache.Entry cacheEntry = mCache.get(request.getCacheKey());                
                        if (cacheEntry != null) {                    
                            networkResponse = new NetworkResponse(cacheEntry.data, cacheEntry.responseHeaders);                    
                            response = request.parseNetworkResponse(networkResponse);                
                        }            
                    } else if (request.shouldCache() && response.cacheEntry != null) {                        
                        mCache.put(request.getCacheKey(), response.cacheEntry);                
                        request.addMarker("network-cache-written");            
                    }           
                    // Post the response back.           
                    request.markDelivered();            
                    mDelivery.postResponse(request, response);        
               } catch (VolleyError volleyError) {                    
                    volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);                  
                    parseAndDeliverNetworkError(request, volleyError);        
               } catch (Exception e) {            
                   VolleyLog.e(e, "Unhandled exception %s", e.toString());            
                   VolleyError volleyError = new VolleyError(e);                    
                   volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);                    
                   mDelivery.postError(request, volleyError);       
               }    
          }
    }
    

    从代码中可以看到,request在即将运行之前,首先会判断一次isCanceled(),假如我们在这之前已经将request取消了,那么request也就直接结束了,此时一般情况下不会出现内存泄露的情况,假如在那之后我们才调用cancel操作,那么我们继续往下看,此时run函数继续,request进入到performRequest阶段,然后最后postResponse。
    我们会用到cancel操作的情况一般有:
    1.不关心这个request的结果了,主动cancel,但是activity没有被关闭;
    2.在activity关闭时,cancel掉所有这个activity发出的request请求。我们在使用request时,还需要传入Response.Listener和Response.ErrorListener的接口,用来当request请求结束时传数据。而我们在Response的接口中一般都要修改UI,这就意味着这个接口会持有对Activity的引用,所以这种情况下,Activity关闭,request虽然被cancel了,但是request还持有对Activity的引用,导致Activity的内存泄露

    解决

    解决办法有两种:

    1.新建一个自己的Request类

    这里以StringRequest为例,那么直接上源码

    public class MyStringRequest extends StringRequest{    
        public MyStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {        
            super(method, url, listener, errorListener);    
        }    
        public MyStringRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {        
            super(url, listener, errorListener);    
        }    
        @Override    
        public void cancel(){        
            super.cancel();        
            onFinish();    
        }
    }
    

    onFinish函数会把listener直接设为空(onFinish函数为protected,所以只能在子类里调用了),而cancel操作会把errorListener设为空。

    2.使用弱引用

    现在的项目都是大部分使用的是MVP模式,一般情况下,我们是在Presenter中来实现Response的接口,使用的使用就直接XXXRequest request = new XXXRequest(method,url,this,this);
    下面上改良好的代码:

    MyResponseListener:
    public class MyResponseListener<T extends BasePresenter> implements Response.Listener, Response.ErrorListener {    
        private WeakReference<Response.Listener> listenerRef;    
        private WeakReference<Response.ErrorListener> errorRef;    
        public MyResponseListener(Response.Listener listener, Response.ErrorListener error) {        
            listenerRef = new WeakReference<>(listener);        
            errorRef = new WeakReference<>(error);   
        }    
        @Override    
        public void onErrorResponse(VolleyError error) {        
            if (errorRef.get()!=null){            
                errorRef.get().onErrorResponse(error);        
            }    
        }    
        @Override    
        public void onResponse(Object response) {       
            if (listenerRef.get()!=null){            
                listenerRef.get().onResponse(response);        
            }    
        }
    }
    
    BasePresenter:

    这里可以再做一层保护,自定义一个接口,让Presenter来实现这个接口,防止被人直接使用new XXXRequest(method,url,this,this)。

    public abstract class BasePresenter implements Response.Listener, Response.ErrorListener {                
        private MyResponseListener listener;    
        public BasePresenter() {        
            initListener();    
        }    
        protected void initListener() {        
            listener = new MyResponseListener(this, this);    
        }
        protected Response.Listener getListener(){    
            return listener;
        }
        protected Response.ErrorListener getErrorListener(){    
            return listener;
        }
    }
    

    相关文章

      网友评论

          本文标题:Volley与内存泄露

          本文链接:https://www.haomeiwen.com/subject/iafrsttx.html