我遇到內存泄漏問題。當我展示一個活動時,每件事情都有效。當我按回來並嘗試重新加載活動時,我得到一個outOfMemoryException。Android內存泄漏解決方案
所以從我讀過的文檔中可以得出結論,在這個活動中,並不是所有的引用都被刪除,所以活動不會被垃圾回收器回收(因爲具有活動引用的活動不會被gc收集)。
例如下面的代碼可能導致內存泄漏(假設有少量內存可用)?因爲我初始化gestureDetector但我從來沒有uninitialise它:
public class FotoGallery extends Activity {
private GestureDetector gestureDetector;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector = new GestureDetector(new MyGestureDetector());
}
}
編輯:我已經有這個問題,當我在一個ImageView的設置圖像。
public class FotoGallery extends Activity {
private GestureDetector gestureDetector;
private String path = "/mnt/sdcard/DCIM/img001.jpg";
private Bitmap currentBitmap;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector = new GestureDetector(new MyGestureDetector());
setImage(path);
}
private static final int SWIPE_MIN_DISTANCE = 30;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//rightFling detected
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//leftFling detected
}
} catch (Exception e) {
// nothing
}
return false;
}
}
private void setImage(String path) {
if (currentBitmap != null) {
currentBitmap.recycle();
}
final ImageView imageView = (ImageView) findViewById(R.id.imageview);
currentBitmap = BitmapFactory.decodeFile(path);
imageView.setImageBitmap(currentBitmap);
}
}
Now my final question is how can you uninitialise all the variables at the right time? Do you specifically need to listen for when a user pr
esses回來,然後把所有的變量爲空?
我添加了圖像加載代碼,這也導致內存泄漏 – Vincent 2011-04-28 09:17:02
我還沒有真正玩過位圖處理恐怕,但似乎有很多關於它的線程和類似,雖然從我可以告訴在Google上。你有沒有嘗試發佈在http://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966(78分之一)的答案?恐怕我沒有多大用處。 :/ http://stackoverflow.com/questions/5697760/android-out-of-memory-exception-when-creating-bitmap也有一個很好的鏈接列表。 – Klaus 2011-04-28 10:07:49
以下是查找內存泄漏過程的非常好的資源:https://www.linkedin.com/pulse/fixing-memory-leaks-android-studio-albert-lai – rakoonise 2015-03-27 05:58:11