Some scenarios for Android memory leaks.

Source: Internet
Author: User

Recently, in maintaining the code, it was found that a custom view (this view was created in a asynctask worker thread Doinbackground, added to the window in the UI thread OnPostExecute) often leaks memory. The activity that causes it to be referenced is not released, and each time it exits, it causes the activity's object to be +1.

Package Com.xxx.launcher.view;import android.content.context;import android.util.log;import android.view.View; Public classWeathertextview extends Skintextview { Public Weathertextview  (context context) {
Super (context); Postdelayed (mshowcityrunnable,
$);// This step has a problem } @Overrideprotected voidOnwindowvisibilitychanged (intvisibility) {super.onwindowvisibilitychanged (visibility); if(Visibility = =view.visible) {post (mshowcityrunnable); }} @Overrideprotected voidOndetachedfromwindow () {Super.ondetachedfromwindow (); OnCancel (); }; Public voidOnCancel () {removecallbacks (mshowcityrunnable); } PrivateRunnable mshowcityrunnable =NewRunnable () {@Override Public voidrun () {LOG.I ("mshowcityrunnable-------TAG","Run"+mshowcityrunnable); SetText (city); } };}

Finally, through the mat tool to see the comparison of memory snapshots, found the following situation, the memory leaks in the place locked in the second inner class of Weathertextview$2 mshowcityrunnable, at first it was never imagined that the inner class where there is a leak, Finally suddenly a flash of light, is not the view of the post () method caused by a search on the internet, found indeed.

 public   Boolean post (Runnable action) {      Handler Handler;      Attachinfo attachinfo  = Mattachinfo;  if  (attachinfo! = null   = Attachinfo.mhandler;  else   { //  Assume that post would succeed later   return  true  ;   return   Handler.post (action); }  

In the post () function note, it is explicitly written: the This method can be invoked from outside of the UI thread if this View was attached to a window.

When the view is not attach to the current window, the Mattachinfo value is null, so the else statement is executed, and then the Getrunqueue () and its post () methods are seen:

StaticFinal threadlocal<runqueue> srunqueues =NewThreadlocal<runqueue>(); Staticrunqueue Getrunqueue () {Runqueue RQ= Srunqueues.Get(); if(RQ! =NULL) {           returnRQ; } RQ=NewRunqueue (); Srunqueues.Set(RQ); returnRQ; } ...StaticFinalclassRunqueue {PrivateFinal arraylistNewArraylist(); voidPost (Runnable action) {postdelayed (action,0); }         voidPostdelayed (Runnable Action,LongDelaymillis) {handleraction handleraction=Newhandleraction (); Handleraction.action=Action; Handleraction.delay=Delaymillis;           Synchronized (mactions) {mactions.add (handleraction); }       }               voidexecuteactions (Handler Handler) {synchronized (mactions) {final ArrayListmactions; FinalintCount =actions.size ();  for(inti =0; I < count; i++) {Final handleraction handleraction= actions.Get(i);               Handler.postdelayed (Handleraction.action, Handleraction.delay);           } actions.clear ();  } } ...... } 

This will insert the runnable into a static threadlocal Runqueue team joins (post in the worker thread, insert the worker thread's runqueue queue), and for the example given at the beginning of this article, when will the inserted runnable be executed? ?

There is only one place to call the Runqueue.executeactions () method, which is in the following non-static method of the Viewrootimpl class

Private void performtraversals () {                if (mlayoutrequested &&! ) mstopped) {              //  Execute enqueued actions on every layout in case a view this was detached              
   
    // 
     enqueued an action after being detached  
                getrunqueue (). Executeactions ( Attachinfo.mhandler);          }  }  
   

The method is executed on the UI thread (see Viewrootimpl.handlemessage ()), so when the UI thread executes to Getrunqueue () in the Performtraversals (), it gets the runqueue in the UI thread, In this way, the runqueue in the asynctask thread is never executed and Asynctask is implemented with a thread pool, and the Asynctask-initiated thread will persist for a long time, resulting in the following referential relationship:

Asynctask thread = = Static Threadlocal Runqueue = Runnable = View=> Activity;

So even if the activity is finished, there is always a static reference chain referencing the activity, and activity generally refers to a lot of resources, compared to tablets, which eventually lead to serious resource leaks.

In the end, I wrote a change.

Package Com.xxx.launcher.view;import android.content.context;import android.util.log;import android.view.View; Public classWeathertextview extends Skintextview { PublicWeathertextview (Context context) {super (context); } @Overrideprotected voidOnattachedtowindow () {Super.onattachedtowindow (); Postdelayed (mshowcityrunnable, $);//to execute the POST method in the Onattachedtowindow method} @Overrideprotected voidOnwindowvisibilitychanged (intvisibility)            {super.onwindowvisibilitychanged (visibility); if(Visibility = =view.visible) {post (mshowcityrunnable); }} @Overrideprotected voidOndetachedfromwindow () {Super.ondetachedfromwindow ();    OnCancel ();        };  Public voidOnCancel () {removecallbacks (mshowcityrunnable); }    PrivateRunnable mshowcityrunnable =NewRunnable () {@Override Public voidrun () {LOG.I ("mshowcityrunnable-------TAG","Run"+mshowcityrunnable);        SetText (city); }    };}

So the activity is no longer referenced by other things, there will be no activity leakage, the activity can be released. This way, no matter how many timesthe entry exits into this mainmenuactivity,the Mainmenuactivity object will only save one copy.

PS: As to why the mainmenuactivity+1 is shown in the two histogram (histogram) comparison chart, it is because this is the class name, and after the class is loaded, it will not be recycled until the process is finished.

=============================================================================================================== ================

=============================================================================================================== ================

This leak is generally due to mstoragemanager registration, but no cancellation.

Mstoragemanager = (StorageManager) Mcontext.getsystemservice (Context.storage_service); Mstoragemanager.registerlistener (Mstoragelistener);

You can cancel the registration.

if NULL ) {    mstoragemanager.unregisterlistener (mstoragelistener);}

Some scenarios for Android memory leaks.

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.