2012-04-10 2 views
1

보기와 타이머를 만드는 매우 간단한 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);  
    } 
} 
+0

ddms 및 MAT에서 할당 추적 프로그램을 사용하면 안되는 이유가 있습니까? – jqpubliq

+0

둘 다 수동적으로 메모리 누수를 알리기 때문입니다. 메모리 누수가 감지되면 화면에 무언가가 나타납니다. –

답변

0

당신은이 Romainguy에서 좋은 게시물이 스스로

+0

문제는 타이머가 아니며 "setTextColor"(질문이 수정 됨)에 대한 호출입니다. –

0

코딩보다 http://developer.android.com/reference/android/widget/Chronometer.html

많은 쉽게 안드로이드 크로노 미터 클래스에 내장 사용할 수 있습니다 다음과 같이

활동입니다 메모리 누수에 관해서 :

Avoiding memory leaks

+0

맞아, 나는이 기사에 익숙하지만이 문제를 다루지 않는다. 이것은 매우 간단한 예이며 메모리 누수 없이는 불가능하다고 생각하는 것이 어렵습니다. 누구든지 할당 된 메모리에 변화가 없기 때문에 표시된 텍스트가 녹색으로 유지되도록 기존 코드를 수정할 수 있습니까? –

0

내 문제에 대한 해결책을 찾았습니다. 표시된 텍스트 색상을 업데이트하면 24 바이트 메모리가 할당되었습니다. 이를 위해 텍스트 색상을 업데이트 할 때만 일정한 양의 메모리를 사용할 수있었습니다.

관련 문제