Android Some thoughts about OutOfMemoryError

Source: Internet
Author: User

A lot of times, we don't have much problem using bitmap. However, when the machine resources are not enough, many applications will be reported OutOfMemoryError, of course, reported such an exception is often given to bitmap memory when memory is not enough. Even a small picture, there will be errors, how to solve it?

My solution is as follows:

[Java] view plaincopy

  1. Public StaticBitmap CreateBitmap (intwidth,intheight, bitmap.config Config) {  

  2. Bitmap Bitmap = null;

  3. Try  {  

  4. Bitmap = Bitmap.createbitmap (width, height, config);

  5.      } catch

  6. while (bitmap = = null) {

  7. System.GC ();

  8. System.runfinalization ();

  9. Bitmap = CreateBitmap (width, height, config);

  10. }

  11. }

  12. }


Recent experiments have shown that when memory leaks are large, the above approach simply does not prevent memory overflow. In fact, to avoid memory overflow or to rely on the usual writing code when you pay attention to. Many times the overflow is mainly due to the bitmap and drawable resources are not released, especially when the project is a lot of picture resources, this problem is particularly prominent.

Workaround: After CreateBitmap, when this bitmap is exhausted, it needs to recycle this resource.

There is also the need to change the background resources of the picture need to use to drawable, when the need to replace the drawable, the original drawable need setcallback (NULL) to enable the activity to dereference the original resource, so that the resources are freed. Java memory management is not like C + + general, but there is its flexibility, as long as you think about it, you can manage the memory well.

If you have a better solution, you can discuss it together.


Android Some thoughts about OutOfMemoryError

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.