您的位置:首页 > 其它

Volley中listener导致的内存泄露

2016-04-26 11:38 363 查看
项目中用Volley作为http框架,封装了一个JsonRequest,性能优化的时候,LeakCanary一直提示Volley的listener内存泄露,检查了很久也没发现哪里出现内存泄露

public class JsonRequestImpl extends JsonRequest<JSONObject > {
public JsonRequestImpl(int method, String url,
JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(  method,
url,
(jsonRequest == null) ? null : jsonRequest.toString(),
listener,
errorListener);
}

public JsonRequestImpl(String url,
JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
this(  jsonRequest == null ? Request.Method.GET : Request.Method.POST,
url,
jsonRequest,
listener,
errorListener);
}

/**
* @param response
* @return
*/
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}

/**
* 设置超时
* @return
*/
@Override
public RetryPolicy getRetryPolicy() {//设置超时
RetryPolicy retryPolicy= new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return retryPolicy;
}

/**
* 设置header
* @return
* @throws AuthFailureError
*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {//添加header
Map<String,String> map=new HashMap<String,String>();
map.put("Accept", "application/json");
map.put("Content-Type", "application/json; charset=UTF-8");
return map;
}
}

获取Volley请求队列的时候

requestQueue = Volley.newRequestQueue(context.getApplicationContext());

并没有直接传进Activity实例进来,而是使用全局唯一的context上下文。

发送请求的时候加TAG,界面离开前台的时候直接在onPause里边取消标记为TAG的网络请求。

还是找不到内存泄露的原因,网上查了下资料,说是Volley自己的一个小bug

原来使用的Volley版本是:

compile 'eu.the4thfloor.volley:com.android.volley:2015.01.06'

改为
compile 'com.mcxiaoke.volley:library:1.0.19'


后果然就不再提示内存泄露的问题了

unofficial mirror (with some minor bugfix) for volley.

点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: