У меня очень простая активность в Android, которая создает представление и таймер. Задача таймера обновляет пользовательский интерфейс при вызове «setTextColor». При выполнении я замечаю, что память выделяется «java.util.concurrent.CopyOnWriteArrayList», вызванная вызовом «setTextColor». Есть ли способ избежать этого? Мое намерение состоит в том, чтобы запустить этот простой таймер, который контролирует память без изменения потребляемой памяти.Обновление 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
Потому что оба только пассивно уведомили вас о утечке памяти. Я хочу что-то на экране, которое изменяется при обнаружении утечки памяти. –