Android memory leak analysis and processing

Source: Internet
Author: User
<span id="Label3"></p>What is a memory leak<br>Java uses a forward graph mechanism to automatically check objects in memory through a gc, and if the GC discovers that one or a group of objects is unreachable, it reclaims the object from Memory. That is, an object is not pointed to by any reference, and the object is reclaimed when it is discovered by the GC.<br><br>Reasons for memory leaks<br>1. Memory leaks due to resource object not shutting down<br>Resource objects such as (cursor,file files, etc.) often use some buffering, we should close them in time when we are not in use, so that their buffers can recover memory in Time. Their buffering exists not only in the Java virtual machine, but also outside the Java virtual machine. If we simply set its reference to null without shutting them down, it often causes a memory Leak. Because some resource objects, such as Sqlitecursor (in the destructor finalize (), if we do not close it, it itself will close () closed), if we do not close it, the system will be recycled it also closed it, but this is too low efficiency. therefore, when the resource object is not in use, it should call its close () function, close it, and then set it to Null. be sure that our resource objects are closed when our program Exits.<br>The process of querying the database is often done, but there are often cases where the cursor is not closed after it has been used. If our query result set is relatively small, the memory consumption is not easy to find, only in the case of a large number of operations in a constant time to reproduce the memory problem, which will give future testing and troubleshooting difficulties and risks.<br>Example Code:<br>cursor cursor = getcontentresolver (). query (uri ...);<br>If (cursor.movetonext ()) {<br>... ...<br>}<br>To fix the sample code:<br>cursor cursor = null;<br>try {<br>cursor = getcontentresolver (). query (uri ...);<br>If (cursor! = null &&cursor.movetonext ()) {<br>... ...<br>}<br>} finally {<br>If (cursor! = Null) {<br>try {<br>Cursor.close ();<br>} catch (Exception E) {<br>Ignore this<br>}<br>}<br>}<br>2. When constructing adapter, no cached Convertview is used<br>To construct the baseadapter of a listview, for example, a method is provided in Baseadapter:<br>Public View getView (int position, viewconvertview, viewgroup Parent)<br>To provide the ListView with the View object that each item NEEDS. initially, the ListView instantiates a certain number of view objects from the Baseadapter based on the current screen layout, and the ListView caches the View Objects. When you scroll up the listview, the View object that was originally on the top list item is recycled and then used to construct the newly-appearing list Item. This construction process is done by the GetView () method, and the second parameter view convertview of GetView () is the view object of the cached list item (the cache does not have a view object when it is initialized, and Convertview is Null.) )。 It can be seen that if we do not use convertview, but each time in the GetView () to re-instantiate a view object, that is, wasting resources is also a waste of time, it will also make memory consumption more and More. The process of retrieving the View object of the list item can be viewed by the Listview:<br>Android.widget.AbsListView.java--voidaddscrapview (View Scrap) Method.<br>Example Code:<br>Public View getView (int position, viewconvertview, viewgroup Parent) {<br>View view = new Xxx (...);<br>... ...<br>Return view;<br>}<br>To fix the sample code:<br>Public View getView (int position, viewconvertview, viewgroup Parent) {<br>View view = null;<br>If (convertview! = Null) {<br>View = convertview;<br>Populate (view, GetItem (position));<br>...<br>} else {<br>view = new Xxx (...);<br>...<br>}<br>Return view;<br>}<br>3.Bitmap object is not in use call recycle () to free memory<br>Sometimes we will manipulate the bitmap object manually, if a bitmap object compares memory, when it is not in use, you can call the Bitmap.recycle () method to reclaim the memory occupied by the pixel of this object, but this is not necessary, depending on the Situation. You can look at the comments in the Code:<br>/**<br>* Free up the memory associated with Thisbitmap ' s pixels, and mark the<br>* Bitmap as "dead", meaning Itwill throw an exception if Getpixels () or<br>* SetPixels () is called, and would drawnothing. This operation cannot is<br>* reversed, So it should is called ifyou is sure there is no<br>* Further uses for the BITMAP. This is anadvanced call, and normally need<br>* Not being called, since the normal gcprocess would free up this memory when<br>* There is no more references to thisbitmap.<br>*/<br>4. Try to use the context of application to replace the context associated with activity<br>This is a very cryptic case of a memory Leak. There is an easy way to avoid context-related memory leaks. The most notable one is to avoid the context escaping from his own range. Use Application Context. The life cycle of this context is as long as the lifetime of the application, rather than depending on the Activity's life Cycle. If you want to keep a long-lived object, and this object needs a context, remember to use the application Object. can be obtained by calling Context.getapplicationcontext () or activity.getapplication (). See this article for more information on how to avoid Android memory leaks (see http://www.linuxidc.com/Linux/2012-02/52951.htm).<br>5. Memory leaks due to registration not canceled<br>Some Android programs may refer to the objects of our anroid program (such as the registration mechanism). Even though our Android program is over, other reference programs still have a reference to an object in our Android program, and the leaked memory is still not garbage collected. Unregisterreceiver was not called after calling Registerreceiver.<br>For example, Suppose we want to listen to the telephony service in the system in the lock screen (lockscreen) to get some information (such as signal strength, etc.), You can define a Phonestatelistener object in the Lockscreen. Register it with the Telephonymanager service at the same time. For Lockscreen objects, A Lockscreen object is created when the lock screen needs to be displayed, and the Lockscreen object is released when the lock screen Disappears.<br>however, If you forget to cancel the Phonestatelistener object that we previously registered when releasing the lockscreen object, it will cause Lockscreen to be garbage collected. If the lock screen interface is constantly displayed and disappears, it will eventually cause outofmemory due to the fact that a large number of Lockscreen objects have no way to be recycled, causing the system_process process to hang Out.<br>Although some system programs, it seems that it can be automatically unregistered (of course, not in time), but we should still clear in our program to unregister, the end of the program should be all the registration is Canceled.<br>6. Memory leaks caused by objects not cleaned up in the collection<br>We usually add references to some objects to the collection, and when we don't need the object, we don't clean up its references from the collection, so the collection gets Bigger. If the set is static, the situation is even worse.<br>Memory leaks in 7.Android using handler<br>Handler Mhandler = new Handler () {<br>@Override<br>public void Handlemessage (Message Msg) {<br>Mimageview.setimagebitmap (mbitmap);<br>}<br>}<br>The above is a simple use of handler. When you use an inner class (including an anonymous class) to create a handler, the handler object implicitly holds an external class object (typically a reference to an activity). Handler usually comes along with a time-consuming background thread (for example, pulling pictures from the web), which notifies handler via a message mechanism after the task has finished executing (the sample is downloaded), and then handler updates the image to the Interface. however, If the user shuts down the activity during a network request, and normally the activity is no longer in use, it may be reclaimed during GC inspection, but since the thread has not finished executing and the thread holds the handler reference, the handler holds activity, the activity cannot be recycled (that is, memory Leaks) until the end of the network request (the sample download is complete). also, if the handler postdelayed () method is executed, the method loads the handler into a message and pushes the message into the messagequeue, before the set delay arrives, There will be a chain of activity, messagequeue, message, Handler, which causes the activity to be held in a reference and cannot be recycled.<br><br>Damage to memory leaks<br>The virtual machine consumes too much memory, causing oom (memory overflow), and a program Error. For Android apps, The user opens an activity, closes it after use, leaks it, turns it off, and leaks it, and then, several times, the program consumes more memory than the system limits, FC.<br><br>Workarounds for memory leaks using handler<br>1. Protection through program LOGIC.<br>(1) A background thread that is stopped when activity is Closed. When the thread is stopped, it is equivalent to cutting off the handler and externally connected lines, and the activity will naturally be recycled at the right Time.<br>(2) if the handler is a message with delay, then use the corresponding Handler's removecallbacks () method to remove the messaging object from the message Queue.<br>2. Declare handler as a static class.<br>Static classes do not hold objects of external classes, so activity can be recycled at Will. The code is as Follows:<br>Static class MyHandler extends Handler {<br>@Override<br>public void Handlemessage (Message Msg) {<br>Mimageview.setimagebitmap (mbitmap);<br>}<br>}<br>But That's still a problem. because handler no longer holds references to external class objects, the program does not allow objects in the activity to be manipulated in Handler. So you need to add a weak reference to activity in handler (weakreference):<br>Static class MyHandler extends Handler {<br>Weakreference<activity > mactivityreference;<br><br>MyHandler (activity Activity) {<br>mactivityreference= New Weakreference<activity> (Activity);<br>}<br><br>@Override<br>public void Handlemessage (Message Msg) {<br>Final activity activity = Mactivityreference.get ();<br>If (activity! = Null) {<br>Mimageview.setimagebitmap (mbitmap);<br>}<br>}<br>}<br><br>Extension: What is weakreference?<br>WeakReference a weak reference, as opposed to a strong reference (which we often refer to), is characterized by the fact that the GC ignores weak references when it recycles, that is, even if a weak reference points to an object, as long as the object is not pointed to by a strong reference (and most often requires no soft reference. But the concept of soft references here can be ignored, and the object is reclaimed when it is checked by the GC. For the above code, after the user has closed the activity, even though the background thread is not finished, the GC will still recycle the activity while checking because only one weak reference from handler points to Activity. In this way, the problem of memory leaks will not occur.<br><br>So what is the effective way to detect memory usage and memory leaks in Android development?<br>Here are three ways to Focus:<br>1. Log information of the program<br>When the program is garbage collected, a log message (logcat Window) is printed, for example:<br>D/DALVIKVM (9050): gc_concurrent freed 2049K, 65% free 3571k/9991k, external 4703k/5261k, paused 2ms+2ms<br>Note the "3571k/9991k" value in this message, which represents the size of the heap used by the program, and if the value has been increasing and never decreasing, then there is a memory leak in the program that represents it.<br>2. Heap Information for DDMS<br>The Eclipse development environment also provides a more intuitive way to view the heap information for an app as Follows:<br>Android Development practice: detecting memory footprint and leaks in apps<br>(1) Connect the phone, run the program, assuming the Com.ticktick.test program<br>(2) Click the Ddms button to select the program (com.ticktick.test) to be detected in the device window on the left.<br>(3) Click on the second icon in the Device window toolbar (Update Heap),<br>(4) Click the Cause GC button on the right window to get the heap information of the current Program.<br>similarly, as the program runs, multiple clicks to get the heap size, if only increase, it also indicates that the program has a memory Leak.<br>3. ADB command to view memory information<br>In fact, the most comprehensive and simplest way is to use the ADB command to view the memory footprint and memory leaks of the program, open a command-line window, the format of the ADB command is as Follows:<br>adb shell Dumpsys meminfo <package_name><br>Among them, Package_name can also be replaced by program Pid,pid can be through the adb shell top | grep app_name to Find.<br><br>(1) Heap information for Native/dalvik<br>Specifically in the first and second lines above, it gives the JNI layer and the Java layer of memory allocation, if it is found that the value has been increasing, the representative of the program may have a memory Leak.<br>(2) PSS information for total<br><p><p>This value is the amount of memory that the app really occupies, and with this information, it's easy to identify which programs in the phone account for the larger memory.</p></p><p><p><br></p></p><p><p>Welcome to the public account<br></p></p><br><p><p></p></p><p><p><br></p></p><p><p>Android memory leak analysis and processing</p></p></span>

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.