Android应用程序的内存分析(2)

调试一个内存泄露实例:


在Dalvik运行时里边,程序员不能显式地分配和释放内存,所以这里的内存泄露跟c和c++里面的不同。在你的代码里边,内存泄露就是你保留了一个并不再需要的类对象的引用。有时候仅仅一个引用就会阻碍gc对一大堆对象的回收。

我们来过一个实际的例子,Android SDK里面提供的范例程序Honeycomb Gallery sample app 。它是一个photo gallery程序,用来演示一些新的Honeycomb API的使用。(下载和编译这些代码,请看这些命令 。)我们会有意地加入一个内存泄露在程序里边,然后来演示如何调试它。

Android应用程序的内存分析


想象一下我们想修改程序让它从网络下载图片。为了让它更具备灵活性,我们可以考虑实现一个缓存,保存最近查看过的图片。我们可以对ContentFragment.java做一些小的修改来达到这个目的。在class顶部,我们增加一个新的静态变量:

private static HashMap<String,Bitmap> sBitmapCache = new HashMap<String,Bitmap>();  

这里就是我们保存缓存的地方。现在我们可以修改updateContentAndRecycleBitmap()方法,让它在下载之前先查看是否数据已经存在,如果不存在就去下载,然后添加数据到缓存。

void updateContentAndRecycleBitmap(int category, int position) {        if (mCurrentActionMode != null) {            mCurrentActionMode.finish();        }             // Get the bitmap that needs to be drawn and update the ImageView.             // Check if the Bitmap is already in the cache        String bitmapId = "" + category + "." + position;        mBitmap = sBitmapCache.get(bitmapId);             if (mBitmap == null) {            // It's not in the cache, so load the Bitmap and add it to the cache.            // DANGER! We add items to this cache without ever removing any.            mBitmap = Directory.getCategory(category).getEntry(position)                    .getBitmap(getResources());            sBitmapCache.put(bitmapId, mBitmap);        }        ((ImageView) getView().findViewById(R.id.image)).setImageBitmap(mBitmap);    }  

我已经在这里故意引入了一个内存泄露的问题:我们把图片加入了缓存但是从来没有移除他们。在真实的应用里,我们可以会用某种方法来限制缓存的大小。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwxjwx.html