我遇到内存泄漏问题。当我展示一个活动时,每件事情都有效。当我按回来并尝试重新加载活动时,我得到一个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