PowenKo, Android Tutorial 091, System, Memory Leaks


Memory Leaks

reference:

http://developer.android.com/resources/articles/avoiding-memory-leaks.html

 

 

經常犯的錯誤:

錯誤1.

@Override
protected void onCreate(Bundle state) {
  super.onCreate(state);
  
  TextView label = new TextView(this);
  label.setText("Leaks are bad");
  
  setContentView(label);
}

錯誤2.
因為當手機螢幕轉時,會重新呼叫onCreate,所請把
大的圖片放在onCreate 外面如下

private static Drawable sBackground;
  
@Override
protected void onCreate(Bundle state) {
  super.onCreate(state);
  
  TextView label = new TextView(this);
  label.setText("Leaks are bad");
  
  if (sBackground == null) {
    sBackground = getDrawable(R.drawable.large_bitmap);
  }
  label.setBackgroundDrawable(sBackground);
  
  setContentView(label);
}

請多用

 Context context=Context.getApplicationContext() or Activity.getApplication().

Leave a Reply