2012-04-10 56 views
1

我有一个非常简单的Android活动,创建一个视图和一个计时器。计时器任务通过调用“setTextColor”来更新UI。执行时,我注意到由“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);  
    } 
} 
+0

是否有理由不应该只在ddms和MAT中使用分配跟踪器? – jqpubliq 2012-04-10 01:36:20

+0

因为两者都只是被动地通知你泄漏内存。我希望在检测到内存泄漏时更改屏幕上的内容。 – 2012-04-10 02:15:46

回答

0

编码它有一个很好的职位从Romainguy关于内存泄漏:

Avoiding memory leaks

+0

对,我很熟悉这篇文章,但没有解决这个问题。这是一个非常简单的例子,我很难相信在没有内存泄漏的情况下不能做到这一点。任何人都可以修改现有的代码,使得显示的文本保持绿色,因为分配的内存没有变化? – 2012-04-10 02:19:03

0

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