正如谷歌所说,当位图不在Android 3.0下使用时,我们必须手动调用Bitmap.recycle(),因为内存保留在本机堆中.
因此,我们可以为Bitmap提供引用计数,并在使用ListView时检查是否需要在ImageView的onDetachedFromWindow()中回收位图.这是来自Google的演示项目Bitmapfun(ImageFetcher)的解决方案.
但是当使用RecyclerView时,convertview通常会被分离并附加.onDetachedFromWindow()可能会回收位图,所以当它再次附加到父级时,位图就会被回收.
如何处理这个问题?使用RecyclerView时,在Android 3.0下回收位图的正确方法是什么?
这是Googls的Demo BitmapFun(ImageFetcher)的解决方案 - 扩展ImageView:
@Override
protected void onDetachedFromWindow() {
// This has been detached from Window, so clear the drawable
setImageDrawable(null);
super.onDetachedFromWindow();
}
@Override
public void setImageDrawable(Drawable drawable) {
// Keep hold of previous Drawable
final Drawable previousDrawable = getDrawable();
// Call super to set new Drawable
super.setImageDrawable(drawable);
// Notify new Drawable that it is being displayed
notifyDrawable(drawable, true);
// Notify old Drawable so it is no longer being displayed
notifyDrawable(previousDrawable, false);
}
private …Run Code Online (Sandbox Code Playgroud) 当使用MONKEY测试我们的应用程序时,我们发现了一个棘手的ANR问题.
CPU和内存使用处于正常水平.
似乎ANR是由一个由MONKEY伪造的Timeout KeyEvent发送到我们应用程序的Activity.以下是日志的一部分:
“
ANR:
Time: 2016-12-29 15:36:08
Window: AppWindowToken{56a48d3 token=Token{abb12c2 ActivityRecord{cb0230d u0 <our app’s activity> t34}}} - Window{40c381a u0 <our app’s activity>}
DispatchLatency: 5005.0ms
WaitDuration: 5003.6ms
Reason: Waiting to send key event because the focused window has not finished processing all of the input events that were previously delivered to it. Outbound queue length: 0. Wait queue length: 1.
ANR:
11: channelName='40c381a <our app’s activity> (server)', windowName='Window{40c381a u0 <our app’s activity>', status=NORMAL, monitor=false, inputPublisherBlocked=false
OutboundQueue: <empty>
WaitQueue: length=1 …Run Code Online (Sandbox Code Playgroud)