由于公司项目时间很久了,目前项目中部分网络请求还是使用过时的android-async-http网络请求库。最近使用内存检测工具(leakcanary),才发现项目中内存泄漏时多么的严重,带着沉重的又好奇的心情开始了。。。内存检测之旅
(1)AsyncHttpClient中提供的get和post方法分为两种:有Context和无Context。下面以post请求方法为例来说明,如下为post的其中三个重载方法:
public void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
this.post((Context)null, url, params, responseHandler);
}
public void post(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
this.post(context, url, this.paramsToEntity(params), (String)null, responseHandler);
}
public void post(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) {
this.sendRequest(this.httpClient, this.httpContext, this.addEntityToRequestBase(new HttpPost(url), entity), contentType, responseHandler, context);
}
读源码可以发现,context对象传进去主要作为 requestMap 的key值,方便后面网络请求的取消。
private final Map>>> requestMap;
protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, AsyncHttpResponseHandler responseHandler, Context context) {
if(contentType != null) {
uriRequest.addHeader("Content-Type", contentType);
}
Future request = this.threadPool.submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));
if(context != null) {
Object requestList = (List)this.requestMap.get(context);
if(requestList == null) {
requestList = new LinkedList();
this.requestMap.put(context, requestList);
}
//这里是把context内发出的http request加入到弱引用List中//重点是context没有弱引用处理,若是没有主动remove掉,可能会引起context内存泄漏 ((List)requestList).add(new WeakReference(request));
}
}
//remove context下发出的网络请求
public void cancelRequests(Context context, boolean mayInterruptIfRunning) {
List requestList = (List)this.requestMap.get(context);
if(requestList != null) {
Iterator var5 = requestList.iterator();
while(var5.hasNext()) {
WeakReference requestRef = (WeakReference)var5.next();
Future request = (Future)requestRef.get();
if(request != null) {
request.cancel(mayInterruptIfRunning);
}
}
}
//这里才会remove掉context
this.requestMap.remove(context); }
==============================================================解决方法:android-async-http网络请求库没有对Context对象做处理,需要我们把传入的Context的弱引用传入进去,即可。例如我是在MainActivity中发出的网络请求,private WeakReferenceweakHttpContext = new WeakReference(this);
在网络请求是,传入weakHttpContext.get() 就可以了
AsyncHttpClient client = new AsyncHttpClient();
ByteArrayEntity entity = new ByteArrayEntity(jsonData.getBytes());
client.post(weakHttpContext.get(), url, entity, "text/plain", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, String content) {
super.onSuccess(statusCode, content);
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
});
=================
以上是就是分享的内容,不喜勿喷。
第一次写文章,有很多不足,希望多提意见