更新Android UI而不会泄漏内存

时间:2012-04-10 00:40:19

标签: android

我有一个非常简单的Android Activity,可以创建一个视图和一个计时器。计时器任务通过调用“setTextColor”更新UI。执行时,我注意到内存是由“java.util.concurrent.CopyOnWriteArrayList”分配的,这是由对“setTextColor”的调用引起的。有办法避免这种情况吗?我的目的是运行这个简单的计时器,它监视内存而不修改消耗的内存。

活动如下:

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);     
    }
}

3 个答案:

答案 0 :(得分:0)

您可以在Android http://developer.android.com/reference/android/widget/Chronometer.html

中使用内置的计时表类

比自己编码容易得多

答案 1 :(得分:0)

Romainguy有一篇关于内存泄漏的帖子很好:

Avoiding memory leaks

答案 2 :(得分:0)

我找到了解决问题的方法。更新显示的文本颜色会产生24字节的内存分配。通过调整,只有当文本颜色更新时,我才能观察到稳定的消耗内存量。