处理OOME android的最佳方式

时间:2013-02-21 21:08:42

标签: android android-alertdialog

我正在尝试将图像设置为带有drawable的自定义对话框中的imageview。我有以下方法

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
        this.setCancelable(false);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        ViewGroup vg = (ViewGroup)inflater.inflate(R.layout.popup, null);
        image= (ImageView) vg.findViewById(R.id.image);
        Uri uri = Uri.parse("android.resource://"+this.getActivity().getPackageName()+"/drawable/p1");
        image.setImageURI(uri);
.
.
return builder.create();
}

它大部分时间运行良好,但在xxxx字节分配时导致内存不足。

我知道这是因为这个

image.setImageURI(uri);

摆脱这个问题的最佳方法是什么?

UPDATE ::

I tried to recycle the bitmap by using this 

Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
        if(!bitmap.isRecycled()){
        bitmap.recycle();
        bitmap =null;
        }

现在,如果我连续拨打相同图像的拨号,我会收到此错误:

Canvas trying to use a recycled bitmap Runtime Exception. 

感谢任何帮助

2 个答案:

答案 0 :(得分:0)

最好的方法是查看应用程序使用的内存量以及使用它的位置。你可能正在某个地方泄漏。如果没有,请弄清楚如何减少总体内存使用量。 Eclipse可以为您提供堆使用转储。

答案 1 :(得分:0)

Eclipse Memory Analyzer(http://www.eclipse.org/mat/)可以与DDMS和堆分析器一起帮助您找到泄漏。

要启动堆更新,您可以从Eclipse中切换到DDMS视图,然后在那里选择与您的应用程序对应的进程,然后您将选择"显示堆更新"按钮。然后每次单击"原因GC"按钮,您将看到堆上对象的更新。

要使用Eclipse进行分析,您可以单击"转储HPROF文件"使用Eclipse Memory Analyzer加载它,这将为您提供有关可能泄漏的更多提示。

这篇关于Android开发者博客的博客文章详细介绍了http://android-developers.blogspot.ca/2011/03/memory-analysis-for-android.html