这是否是将闭包附加到textView的泄漏?
时,countdownTextView是getViewById()和布局视图的一部分。void postCountDownTimer(Long countDownTime, LinearLayout countdownContainer, TextView countdownTextView) {
if (countDownTime >= System.currentTimeMillis()) {
countdownTextView.postDelayed(new Runnable() {
@Override
public void run() {
postCountDownTimer(countDownTime, countdownContainer, countdownTextView);
}
}, COUNTDOWN_DELAY_MILLIS);
}
答案 0 :(得分:1)
是的。只要countDownTime> = System.currentTimeMillis()为true,它将连续将消息发布到UI线程上的Handler。这将保留对countdownTextView和countdownContainer的引用,直到调用该函数并且条件评估为false为止。您确实想使用自己的处理程序来执行此操作,因此您可以删除onStop或onDestroy中的所有消息(最好是onStop,以便您的UI在后台运行时不尝试更新)并删除引用,以免泄漏。>
答案 1 :(得分:1)
在这种情况下,您应该使用Handler()
,因为它会根据您的尝试而导致内存泄漏。 postDelayed
将进入队列,当上下文被破坏时,该队列将停留在后面。
做类似的事情:
private Handler mHandler = new Handler();
void postCountDownTimer(Long countDownTime, LinearLayout countdownContainer, TextView countdownTextView) {
if (countDownTime >= System.currentTimeMillis()) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mHandler.postDelayed(this, COUNTDOWN_DELAY_MILLIS);
}
}, COUNTDOWN_DELAY_MILLIS);
}
}
//then on somewhere when your context gets destroyed, perform the call below:
mHandler.removeCallbacksAndMessages(null);