Handler causes memory leakage analysis

Source: Internet
Author: User

Handler mhandler = new handler (){
@ Override
Public void handlemessage (Message MSG ){
// Do something.
}
}
'''
When we create 'handler' like this, 'android lint' will prompt us with a 'warning: In Android, Handler classes shoshould be static or leaks might occur .'.

I have never carefully analyzed the cause of the leak. First, let's list the main reasons:
-When the 'android' program is created for the first time, a 'logging' object is created by default, and 'logging' processes each 'message' in 'message quee ', the 'logging' of the main thread has the entire application lifecycle.
-'Handler' is associated with 'message queue 'of 'login' when the main line is created, and 'message' is added to the Message Queue. 'message (queued message) 'will hold the current 'handler' reference. When 'logger' processes the current message, it will call 'handler # handlemessage (Message )'. that is to say, before 'login' processes this 'message', there will be a chain 'messagequeue-> message-> Handler-> active ', because of its reference, your 'active' is held for reference and cannot be recycled'
-** In Java, the no-static internal class implicitly holds a reference of the current class. Static internal classes do not exist. **

# Specific analysis
'''Java
Public class sampleactivity extends activity {

Private Final handler mhandler = new handler (){
@ Override
Public void handlemessage (Message MSG ){
// Do something
}
}

@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
// Send a message that is executed 10 minutes later
Mhandler. postdelayed (New runnable (){
@ Override
Public void run (){}
},600000 );

// End the current activity
Finish ();
}
'''
During 'finish () ', the 'message' has not been processed. 'message' holds 'handler' and 'handler' holds 'activity ', this will prevent the 'active' from being recycled and cause memory leakage.

# Solution
-Program Logic is used for protection.
-If 'handler' is a time-consuming operation, stop your background thread when 'active' is disabled. When the thread is stopped, it is equivalent to breaking the line connecting 'handler' to the external connection. 'active' will be recycled when appropriate.
-If 'handler' is referenced by 'message' of 'delay () 'method: Call the 'handler' 'remove * 'method to remove the message object from the message queue.
-About the 'handler. Remove * 'Method
-'Removecallbacks (runnable R) '-- clears the message on the R match.
-'Removec4allbacks (runnable R, object token) '-- clears the message that matches the R and matches the token (message. OBJ). If the token is null, only the R is matched.
-'Removecallbacksandmessages (Object token) '-- clears the message on the token match.
-'Removemessages (INT what) '-- match by what
-'Removemessages (INT what, object) '-- match by what
We need to clear all 'message (callback) 'whose 'handler' is 'target' and call the following method to 'handler. removecallbacksandmessages (null )';
-Declare 'handler' as a static class.
Static classes do not hold external class objects, so your 'activity' can be recycled at will. But does not hold the reference of 'active'. How do I operate some objects in 'active? Weak references are used here.

'''Java
Public class myactivity extends activity {
Private myhandler mhandler;

@ Override
Protected void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Mhandler = new myhandler (this );
}

@ Override
Protected void ondestroy (){
// Remove all runnable and message.
Mhandler. removecallbacksandmessages (null );
Super. ondestroy ();
}

Static class myhandler extends handler {
// Weakreference to the outer class's instance.
Private weakreference <myactivity> mouter;

Public myhandler (myactivity activity ){
Mouter = new weakreference <myactivity> (activity );
}

@ Override
Public void handlemessage (Message MSG ){
Myactivity outer = mouter. Get ();
If (outer! = NULL ){
// Do something with outer as your wish.
}
}
}
}

Handler causes memory leakage analysis

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.