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