Analysis and resolution of memory leaks using handler (message mechanism) in Android

Source: Internet
Author: User

Problem Description:

The Handler inner class holds a reference to the external class activity, and if the activity exits and the message that Handler has deferred processing is not processed, the activity will not be recycled, which can cause memory leaks repeatedly.

Solution:

    1, OnDestroy when the message is purged.

Mhandler.removecallbacksandmessages (NULL); All messages are cleared when the parameter is null.

2. Declare handler as static and hold the weak reference to activity.

 Public classMainactivityextendsActivity {Private Static FinalString tag = "Mainactivity"; PrivateTextView mtvshow; PrivateMyHandler Mhandler; Private Static Final intDelay_time = 10000;//set to 5s and 10s to check result.@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);            Setcontentview (R.layout.activity_main); Mhandler=NewMyHandler (mainactivity. This); LOG.E (Tag,"OnCreate"); Mtvshow=(TextView) Findviewbyid (r.id.tv_show); NewThread () {@Override Public voidrun () {mhandler.sendemptymessagedelayed (1, Delay_time); LOG.E (Tag,"Msg Send");        }}.start (); } @Overrideprotected voidOnDestroy () {LOG.E (tag,"OnDestroy"); Super. OnDestroy (); }        Static classMyHandlerextendsHandler {weakreference<MainActivity>mweakactivity; //emphasize weak references             PublicMyHandler (mainactivity activity) {mweakactivity=NewWeakreference<>(activity); } @Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); Mainactivity Activity=Mweakactivity.get (); LOG.E (Tag,"Handlemessage," +msg.what); //5s is empty and 10s is empty-notifies activity to be recycled                if(NULL==activity) {LOG.E (tag,"NULL"); } Else{LOG.E (tag,"NOT NULL"); Activity.mTvShow.setText ("Delay Show"); }            }        }    }

Analysis and resolution of memory leaks using handler (message mechanism) in Android

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.