简体   繁体   English

处理OOME Android的最佳方法

[英]Best way to handle OOME android

I am trying to set an image to an imageview in a custom dialog with a drawable. 我试图在带有可绘制对象的自定义对话框中将图像设置为imageview。 I have the following method 我有以下方法

@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();
}

It runs fine most of time but causes a Out of memory on a xxxx-byte allocation. 它在大多数时间运行良好,但会导致xxxx字节分配的内存不足。

I know it is because of this 我知道是因为这个

image.setImageURI(uri);

What is the best way to get rid of this problem?? 摆脱这个问题的最佳方法是什么?

UPDATE:: 更新::

I tried to recycle the bitmap by using this 

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

Now If i get a dialong with same image consecutively I have this error: 现在,如果我连续收到具有相同图像的Dialong,则会出现此错误:

Canvas trying to use a recycled bitmap Runtime Exception. 

Any help is appreciated 任何帮助表示赞赏

The best way is to look into how much memory the app is using and where it's using it. 最好的方法是调查应用程序正在使用的内存量以及使用位置。 You're probably leaking somewhere. 您可能在某处泄漏。 If not, figure out how to reduce your overall memory usage. 如果不是,请找出如何减少整体内存使用量的方法。 Eclipse can get heap usage dumps for you. Eclipse可以为您获取堆使用情况转储。

The Eclipse Memory Analyzer ( http://www.eclipse.org/mat/ ) can help you find the leak, in conjunction with DDMS and the heap analyzer. Eclipse内存分析器( http://www.eclipse.org/mat/ )可以与DDMS和堆分析器一起帮助您查找泄漏。

To start heap updates, you can switch to the DDMS view from within Eclipse, and in there you would select the process corresponding to your app, and then you would select the "Show heap updates" button. 要开始堆更新,您可以从Eclipse中切换到DDMS视图,然后在其中选择与您的应用程序相对应的进程,然后选择“显示堆更新”按钮。 Then every time you click the "Cause GC" button you'll see an update of the objects on your heap. 然后,每次单击“ Cause GC”(原因GC)按钮,您都会看到堆中对象的更新。

To analyze this with Eclipse, you can then click the "Dump HPROF file" to load it with the Eclipse Memory Analyzer, which will give you more hints on what might be leaking. 要使用Eclipse分析此问题,您可以单击“转储HPROF文件”以将其加载到Eclipse Memory Analyzer中,这将为您提供更多有关可能泄漏的提示。

This blog post on the Android developer's blog goes into a lot more detail: http://android-developers.blogspot.ca/2011/03/memory-analysis-for-android.html Android开发人员博客上的这篇博客文章更加详细: http//android-developers.blogspot.ca/2011/03/memory-analysis-for-android.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM