关于内存泄漏,首先在工程里安装相应插件,在点到相应页面的时候则会有一个工具出现。
1. OrderServiceDialog
Excluded by rule matching field android.os.Message#obj because Prior to ART , a thread waiting on a blocking queue will leak the last dequeued object as a stack local reference .
So when a HandlerThread becomes idle, it keeps a local reference to the last message it received. that message then gets recycled and can be used again. as long as all message are recycled after beingused, this won’t be a problem , because these references are cleared when beingrecycled. However, dialogs create when amessage needs to be sent.
These Message templates holds references to the dialoglisteners , which most likely leads to holding a reference onto the activity in someway.Dialogs never recycle their template Message, assuming these Message instances will get GCed when the dialog is GCed. the combination of the these two things creates a hingh potential for memory leaks as soon as you use dialogs. these memory leaks might be temporary, but some handler threads sleep for a long time.
To fix this, you could post empty messages to the idle handler threads from time to time. this won’t be easy because you cannot access all handler threads, but a librarythat is widely used should consider doing this for its own handler threads.
排除规则匹配字段android.os.Message#obj因为在ART之前,等待阻塞队列的线程将泄漏最后一个出队对象作为堆栈本地引用。
所以当HandlerThread变得空闲时,它会保留对它接收到的最后一个消息的本地引用。该消息然后被再次使用,可以再次使用。只要所有消息在被使用后被回收,这不会是一个问题,因为这些引用在被重新循环时被清除。但是,当需要发送消息时会创建对话框。
这些Message模板保存对dialoglisteners的引用,这最有可能导致在某个操作中保留对该活动的引用.Dialogs从不回收其模板Message,假设当对话框为GCed时,这些Message实例将被GCed。一旦你使用对话框,这两个东西的组合就会产生一个内存泄漏的潜力。这些内存泄漏可能是暂时的,但是一些处理程序线程可以长时间睡眠。
要解决这个问题,您可以不时向空闲的处理程序线程发送空消息。这不容易,因为您无法访问所有处理程序线程,但是一个被广泛使用的库应该考虑为自己的处理程序线程执行此操作。
解决方法:首先添加弱引用,
privateDialogInterface.OnDismissListeneronDismissListener=newDialogInterface.OnDismissListener() {
@Override
public voidonDismiss(DialogInterface dialog) {
dialog.dismiss();
mHandler.sendEmptyMessage(0);
mHandler.removeCallbacksAndMessages(null);
}
};
private static classUpdateHandlerextendsHandler {
WeakReferenceweakReference;
UpdateHandler(OrderServiceDialog dialog) {
weakReference=newWeakReference<>(dialog);
}
@Override
public voidhandleMessage(Message msg) {
super.handleMessage(msg);
OrderServiceDialog dialog =weakReference.get();
if(dialog !=null) {
dialog.selectDateAdapter.cancleSelectUpdateAdapter();
}
}
}
发送一个空message给handler,然后把回调的message都移除掉。
2. 自定义的一个StickerSpan继承了ImageSpan,将activity传入,导致了内存泄漏。解决办法:其实不需要activity,不再传activity。加入真的需要上下文,则最好传入getApplicationContext()。
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15
16.
网友评论