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 One: mhandler.removecallbacksandmessages (NULL);//The null parameter clears all messages.
Solution Two: Declare handler as static and hold a weak reference to activity. Key to see the notes in the program where
public class Mainactivity extends Activity {private static final String tag = "Mainactivity"; Private TextView mtvshow; Private MyHandler Mhandler; private static final int delay_time = 10000; Set to 5s and 10s to check result. @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mhandler = new MyHandler (mainactivity.this); LOG.E (Tag, "onCreate"); Mtvshow = (TextView) Findviewbyid (r.id.tv_show); New Thread () {@Override public void run () {mhandler.sendemptymessagedelayed (1, DELA Y_time); LOG.E (Tag, "msg send"); }}.start (); } @Override protected void OnDestroy () {LOG.E (tag, "OnDestroy"); Super.ondestroy (); } static class MyHandler extends handler{weakreference<mainactivity> mweakactivity; Public MyHandler (mainactivity ACtivity) {mweakactivity = new weakreference<> (activity); } @Override public void Handlemessage (Message msg) {super.handlemessage (msg); Mainactivity activity = Mweakactivity.get (); LOG.E (Tag, "handlemessage," + msg.what); 5s is not NULL, and 10s is null, and the tell's activity is 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 caused by using handler in Android