【发布时间】:2013-07-26 09:22:55
【问题描述】:
我读过一些关于在 android 中释放内存的内容,但我仍然对这种行为感到困惑。就我而言,我测试了一个简单的应用程序,何时分配内存以及何时释放内存。我有两个活动。在 MainActivity 我有一个 ImageView。我通过getResources().getDrawable(int id) 或BitmapFactory.decodeResource(Resources res, int id) 引用了一个可绘制图像。两种方式都肯定是为图片分配内存,但是这个内存不会被释放,即使我销毁了我的activity,回收位图或者设置所有变量为null。
public class MainActivity extends Activity {
private ImageView view;
private Drawable drawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (ImageView) findViewById(R.id.image);
// tried with BitmapFactory.decode...
drawable = getResources().getDrawable(R.drawable.connect);
view.setImageDrawable(dr);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
// tried with and without finish
finish();
}
});
}
@Override
protected void onResume() {
super.onResume();
Double allocated = new Double(Debug.getNativeHeapAllocatedSize())
/ new Double((1048576));
Double available = new Double(Debug.getNativeHeapSize()) / 1048576.0;
Double free = new Double(Debug.getNativeHeapFreeSize()) / 1048576.0;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
System.out.println("SYSO : " + df.format(allocated) + "MB of "
+ df.format(available) + "MB (" + df.format(free) + "MB free)");
System.out.println("SYSO : "
+ df.format(new Double(
Runtime.getRuntime().totalMemory() / 1048576))
+ "MB of "
+ df.format(new Double(
Runtime.getRuntime().maxMemory() / 1048576))
+ "MB ("
+ df.format(new Double(
Runtime.getRuntime().freeMemory() / 1048576))
+ "MB free)");
}
@Override
protected void onDestroy() {
super.onDestroy();
// tried using BitmapFactory and bitmap.recycle()
dr.setCallback(null);
dr = null;
view = null;
System.gc();
Runtime.getRuntime().gc();
}
}
我也在我的第二个活动中记录了内存。我发现,我的应用程序在启动时大约有 8-9MB 运行时内存。在主视图中分配我的图像,让内存增长到大约 20MB。当我用finish() 离开我的活动并使用所有释放的东西(如设置回调null 和回收图像)时,为什么仍然分配第二个活动中的内存?我正在多次恢复第二个活动,但内存仍在分配中。我的第一个活动被破坏了,我该如何释放它的内存?我在没有设置callback = null 或回收位图并完成MainActivity 的情况下测试了该行为。然后每次我恢复MainActivity,每次恢复内存都会增长大约10MB。听起来不错,因为旧的引用不会被破坏,并且每次都会分配一个新的图像。但是为什么第一张图片的初始内存不会被销毁呢?
【问题讨论】:
-
developer.android.com/training/displaying-bitmaps/…。检查这可能会有所帮助。它也是垃圾收集器释放内存的工作。
标签: android memory bitmap out-of-memory