Android this Handler class should is static or leaks might occur

Source: Internet
Author: User



If you define an internal handler class in activity, the following code:


public class MainActivity extends Activity {
 
    private  Handler mHandler = newHandler() {
        @Override
        public void handleMessage(Message msg) {
            //TODO handle message...
        }
 
    };
 
    @TargetApi(11)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler.sendMessageDelayed(Message.obtain(), 60000);
 
        //just finish this activity
        finish();
    }
}


Then running the Android Lint tool will have a memory leak warning:


This Handler class should is static or leaks might occur (com.example.ta.mainactivity.1)

Issue:ensures that Handler classes does not hold on to a reference to an outer class
Id:handlerleak

In Android, Handler classes should is static or leaks might occur. Messages enqueued on the application thread ' s MessageQueue also retain their target Handler. If The Handler is a inner class, its outer class would be retained as well. To avoid leaking the outer class, declare the Handler as a static nested class with a weakreference to its outer class.


The reasons are:


    1. When the Android app starts, it creates a Looper object that applies the main thread, and Looper implements a simple message queue, one for processing the message object inside. The main thread Looper object exists throughout the application life cycle.

    2. When handler is initialized in the main thread, the handler and the Looper message queue are associated. A message sent to the queue of messages refers to the Handler object that sent the message, so that the system can call Handler#handlemessage (message) to distribute processing the message.

    3. In Java, non-static (anonymous) inner classes refer to external class objects. Static inner classes do not reference external class objects.

    4. If the external class is activity, it can cause activity disclosure.


When activity finishes, the deferred message continues to exist for 1 minutes in the main thread message queue and then processes the message. The message references the activity's handler object, and the handler references the activity. These reference objects persist until the message is processed, which prevents the activity object from being recycled, causing the activity disclosure described above.



To modify the problem, simply define the handler class as static by following the lint hint, and then keep the external activity object through WeakReference.


private Handler mHandler = new MyHandler(this);
private static class MyHandler extends Handler{
    private final WeakReference<Activity> mActivity;
    public MyHandler(Activity activity) {
        mActivity = new WeakReference<Activity>(activity);
    }
    @Override
    public void handleMessage(Message msg) {
        System.out.println(msg);
        if(mActivity.get() == null) {
            return;
        }
    }
}


So, when you use an inner class in activity, you need to always consider whether you can control the life cycle of the inner class, and if not, it is best to define it as a static inner class.



        MyHandler ttsHandler = newMyHandler(this); 


        privatevoidtest() {                 ttsHandler.sendEmptyMessage(0);         } 


Android this Handler class should is static or leaks might occur


Related Article

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.