2012-04-10 1 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バイトのメモリ割り当てが発生しました。これを調整することによって、テキストの色が更新されたときにのみ、私は一定量の消費されたメモリを観察することができました。

関連する問題