1、volley引发的NetworkDispatcher
加入!!!!那句话解决
@Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Request<?> request;
while (true) {
//注意!!!!这是防止内存泄露的重点!
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;
}
// Tag the request (if API >= 14)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
}
// 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 (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) {
parseAndDeliverNetworkError(request, volleyError);
} catch (Exception e) {
VolleyLog.e(e, "Unhandled exception %s", e.toString());
mDelivery.postError(request, new VolleyError(e));
}
}
}
2、Volley StringRequest等引起的内存泄漏
(1)在引用StringRequest的地方给request添加tag
request.setTag(REQUEST_TAG);
(2)在不用的时候
@Override
protected void onDestroy() {
super.onDestroy();
RequestManager.getRequestQueue().cancelAll(ShortUrlFactory.REQUEST_TAG);
}
3、EventBus引发的内存泄漏
//取消注册 , 防止Activity内存泄漏
EventBus.getDefault().unregister( this );
4、Webview引发的内存泄漏
(1)//延长webview的生命周期,防止内存泄漏
mContext = this.getContext().getApplicationContext();
(2)在onDestroy时取消webview的绑定,并销毁
@Override
protected void onDestroy() {
super.onDestroy();
if (webView != null) {
// 如果先调用destroy()方法,则会命中if (isDestroyed()) return;
// 这一行代码,需要先onDetachedFromWindow(),再
// destory()
ViewParent parent = webView.getParent();
if (parent != null) {
((ViewGroup) parent).removeView(webView);
}
webView.stopLoading();
// 退出时调用此方法,移除绑定的服务,否则某些特定系统会报错
webView.getSettings().setJavaScriptEnabled(false);
webView.clearHistory();
webView.clearView();
webView.removeAllViews();
webView.destroy();
webView = null;
}
}
5、Surface要release
mSurface.release();