Anonymous Listener of volley request causing memory leak

后端 未结 4 1868
别跟我提以往
别跟我提以往 2021-01-05 07:14

I am using volley library for making web-services call. I made a general class for making all web services call and making service call from there and made anonymous listene

4条回答
  •  一向
    一向 (楼主)
    2021-01-05 07:49

    Generally, Anonymous classes have a strong reference to the enclosing class instance. In your case, that would be SplashScreenActivity. Now I guess, your Activity is finished before you get the response from your server through Volley. Since the listener has a strong reference to enclosing Activity, that Activity cannot be garbage collected until the Anonymous class is finished. What you should do is tag all the requests you are sending with the Activity instance, and cancel all the requests at onDestroy() callback of Activity.

    stringRequest.setTag(activityInstance);
    

    To cancel all pending requests:

    requestQueue.cancellAll(activityInstance);
    

    Also, use Application context inside VolleySingleton to create the RequestQueue.

    mRequestQueue = Volley.newRequestQueue(applicationContext);
    

    Don't use your Activity context there and don't cache your Activity instance inside VolleySingleton.

提交回复
热议问题