보기와 타이머를 만드는 매우 간단한 Android 활동이 있습니다. 타이머 작업은 "setTextColor"를 호출하여 UI를 업데이트합니다. 실행 중일 때, "setTextColor"에 대한 호출로 인해 발생하는 "java.util.concurrent.CopyOnWriteArrayList"에 의해 할당 된 메모리를 알 수 있습니다. 이것을 피할 수있는 방법이 있습니까? 내 의도는 소비 된 메모리를 수정하지 않고 메모리를 모니터링하는이 간단한 타이머를 실행하는 것입니다.메모리 누수없이 Android UI 업데이트
이public class AndroidTestActivity extends Activity
{
Runnable updateUIRunnable; // The Runnable object executed on the UI thread.
long previousHeapFreeSize; // Heap size last time the timer task executed.
TextView text; // Some text do display.
// The timer task that executes the Runnable on the UI thread that updates the UI.
class UpdateTimerTask extends TimerTask
{
@Override
public void run()
{
runOnUiThread(updateUIRunnable);
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
// Super.
super.onCreate(savedInstanceState);
// Create the Runnable that will run on and update the UI.
updateUIRunnable = new Runnable()
{
@Override
public void run()
{
// Set the text color depending on the change in the free memory.
long heapFreeSize = Runtime.getRuntime().freeMemory();
if (previousHeapFreeSize != heapFreeSize)
{
text.setTextColor(0xFFFF0000);
}
else
{
text.setTextColor(0xFF00FF00);
}
previousHeapFreeSize = heapFreeSize;
}
};
// Create a frame layout to hold a text view.
FrameLayout frameLayout = new FrameLayout(this);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
frameLayout.setLayoutParams(layoutParams);
// Create and add the text to the frame layout.
text = new TextView(this);
text.setGravity(Gravity.TOP | Gravity.LEFT);
text.setText("Text");
frameLayout.addView(text);
// Set the content view to the frame layout.
setContentView(frameLayout);
// Start the update timer.
UpdateTimerTask timerTask = new UpdateTimerTask();
Timer timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 500, 500);
}
}
ddms 및 MAT에서 할당 추적 프로그램을 사용하면 안되는 이유가 있습니까? – jqpubliq
둘 다 수동적으로 메모리 누수를 알리기 때문입니다. 메모리 누수가 감지되면 화면에 무언가가 나타납니다. –