Find and fix memory leaks in Android-outofmemoryerror

Source: Internet
Author: User
Tags stack trace

"Editor's note" The writer Rebecca Franks,rebecca, a female programmer from Johannesburg, South Africa, is passionate about Android and has 4 years of experience in Android application development. A bit of a perfectionist who loves food.

This article is the domestic Itom management platform OneAPM compiled rendering, the following is the text.

Memory leaks are prone to problems in Android programs. Unsuspecting developers may cause some memory leaks every day without knowing. You may never notice such errors, or even know they exist. Until you encounter an exception such as the following:

java.lang.OutOfMemoryError: Failed to allocate a 4308492 byte allocation with 467872 free bytes and 456KB until OOMat dalvik.system.VMRuntime.newNonMovableArray(Native Method)at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:609)at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444)at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:988)at android.content.res.Resources.loadDrawableForCookie(Resources.java:2580)at android.content.res.Resources.loadDrawable(Resources.java:2487)at android.content.res.Resources.getDrawable(Resources.java:814)at android.content.res.Resources.getDrawable(Resources.java:767)at com.nostra13.universalimageloader.core.DisplayImageOptions.getImageOnLoading(DisplayImageOptions.java:134)

What? What does that mean? Is my bitmap (bitmap) too big?

Unfortunately, this kind of stack trace tends to be a bit confusing. In general, if you encounter a outofmemoryerror error, nine to Ten is due to a memory leak. When I first encountered this kind of stack trace, I was also puzzled, thinking whether the bitmap is too large ... In fact, I was really wrong.

What is a memory leak?

A memory leak is the failure of a program to dispose of discarded memory, resulting in performance damage or disruption.

How are memory leaks in Android programs generated?

Memory leaks in Android programs are easy to generate, which is part of the problem. However, the biggest problem is the Android context (context) object.

Each app has a global Application context object ( getApplicationContext() ). Each activity is a Context subclass that stores information related to the current activity. Typically, memory leaks are related to leaked activity (leaked activtiy).

Typically, a general developer will pass the context object (the contextual objects) to the required thread. Create some static textviews to store a reference to the activity. But, you know, is this possible?

In this case, if you use Memory monitor you will find that the app's memory usage is increasing, as shown in the following Android memory Monitor:


The case of an Android memory monitor when an app with a memory leak problem is running


After resolving a memory leak problem, the Android memory monitor situation

As you can see, in the first picture, the app will never be able to reclaim a portion of the memory already in use. It used 300MB of memory before the OutOfMemoryError error occurred. The second picture shows that the app can be successfully garbage collected, a portion of the memory, so as to maintain a fairly stable memory usage.

How do I avoid memory leaks?
    • Avoid passing Context objects outside of activity or fragment.
    • Never create static Context or View objects, or store them in static variables. This is the primary sign of memory leaks.

      private static TextView TextView; Do and do
      private static context context; Do and do

    • Always remember to unregister the listener (listeners) in the OnPause () or OnDestroy () method. This includes Android
      Listeners, as well as location services, the Display Manager service, and some custom listeners.

    • Do not store strong references to activities in Asynctasks (asynchronous tasks) or background threads. Activity may be turned off, but
      Asynctask will continue to execute and keep a reference to the activity.

    • If possible, use Context-application (Getapplicationcontext ()) instead of an activity
      The Context object.

    • Try to avoid using non-static inner classes. Storing references inside an Activity or View can cause memory leaks. If you have to store references, use the
      WeakReference.

How do I fix a memory leak problem?

Repairing memory leaks requires a lot of practice, trying, trying, and making mistakes to be successful. Typically, memory leaks are not easy to locate. Fortunately, there are a number of tools available that can help you identify potential leaks.

1. Open Android Studio and open the Android Monitor (monitor) option.
2. Run your app, choose your app from the optional app, and run it.
3, in the app to do some operations to achieve similar results. For example, I opened a new video and played it 50 times. (For this reason, I have written a test procedure.) )
4. The key here is to capture the application before the OutOfMemoryException exception occurs.
5. Click on the memory option in the Android Monitor.

6. You will see a dynamically drawn chart. When you're ready, click "Start Garbage collection (Initiate GC)" (The Red Junk Truck icon).
7. Click "Dump Java heap memory" and wait a few seconds. (Icon with green arrows below the truck icon). This generates a. hprof file that you can use to analyze memory utilization.
8. Unfortunately, the Android Studio Hprof file Viewer does not have all the gadgets of the Eclipse Memory Analyzer. Therefore, you need to install MAT.
9. Run the instructions below to convert the Android. hprof file to a format that MAT can understand. (The Hprof-conv tool is located under the Platform Tools folder of the SDK)

./hprof-conv path/file.hprof exitPath/heap-converted.hprof

10. After the conversion is complete, open the file in the MAT. Select "Leak suspect report (Leak Suspects reports)" and click Finish.

Open Eclipse Memory Analyzer--Select leak suspect report
11, click on the top of the three blue bar icon, "Create a histogram for any collection of objects." You will see a list of objects that occupy memory.

Eclipse Memory Analyzer-Histogram
12. Looking at so many objects may make people not feel the mind. In fact, you can filter by the class name, so I recommend you enter the class name in the class name filter.
Find and fix memory leaks in Android-outofmemoryerror Technology share 6th filter objects in Eclipse Memory Analyzer based on class name

13. Now, we see that VideoDetailActivity there are 9 instances. This is obviously wrong, because we actually only need one. To see who saved VideoDetailActivity the reference, right-click the item, select "Merge Paths to shortest GC root" and click "Exclude all virtual/weak/soft references (exclude all Phantom/weak /soft etc. references). ”

Eclipse Memory Analyzer-the shortest path to merge garbage collection roots

The thread that holds the reference is now displayed. After that, you can trace it to the exact instance where the activity reference was stored.

14, according to the following information, it is clear that there is a Displaylistener object after registration has never been written off.

Eclipse Memory Analyzer-memory leak recognition

Therefore, this memory leak problem can be resolved by invoking the Logoff method on this previously registered display Listener (listener).

DisplayManager displayManager = (DisplayManager) mContext.getSystemService(Context.DISPLAY_SERVICE);displayManager.unregisterDisplayListener(listener);

However, not all memory leaks are so easily found, and some are hard to find. However, hopefully this article will enable you to start looking at the root cause of the problem and avoid potential memory leaks. In addition, there are a number of tools to help you find memory leaks, click here to view them.

Reference Links:

    • Memory analyzers
    • Heap Memory Viewer Introduction
    • Memory Monitor
    • Avoid memory leaks in Android

OneAPM Mobile Insight provides a real user experience as a metric for Crash analysis, monitoring network requests and network errors, and improving user retention. Visit the official website of OneAPM for more application performance optimization experiences and to read more technical articles, visit the OneAPM Official technology blog.

This article was transferred from OneAPM official blog

Original address: http://riggaroo.co.za/fixing-memory-leaks-in-android-outofmemoryerror/

Find and fix memory leaks in Android-outofmemoryerror

Related Article

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.