2012-04-10 92 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字節的內存分配。通過對此進行調整,只有更新文本顏色時,才能觀察到消耗的內存量穩定。