Android: Memory leakage caused by Handler usage, androidhandler

Source: Internet
Author: User

Android: Memory leakage caused by Handler usage, androidhandler
Problem description

Once upon a while, when we used the original Handler method, we had the following Warm prompt:

This Handler class should be static or leaks might occur

The following is a more detailed description (warning on Android Studio, I don't know if it is the same on Eclipse)

Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. if the Handler is using a logoff or MessageQueue for a thread other than the main thread, then there is no issue. if the Handler is using the logoff or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.

The general meaning is:

Once Handler is declared as an internal class, it may cause its external class to be unable to be recycled. If Handler uses logoff or MessageQueue (Message Queue) instead of the main thread (UI thread) in other threads (we usually become worker threads), then there is no such problem. If Handler uses logoff or MessageQueue in the main thread, You need to modify the Handler declaration as follows:
Declare Handler as a static class; instantiate a WeakReference (weak reference) of an external class in the external class and input this object to your Handler during Handler initialization; use the WeakReference object for all referenced external class members.

Solution 1

The above description basically expresses the recommended modification method clearly. The following code is an implementation in my own use. For details, refer:

private CopyFileHandler mHandler;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_appstart);    mHandler = new CopyFileHandler(this);    startCopyDBThread();}private void startCopyFileThread(){    Log.d(TAG, "startCopyDBThread");    new Thread(new Runnable() {        @Override        public void run() {            //DO SOMETHING LIKE: copyDBFile();            Message msg=mHandler.obtainMessage();            mHandler.sendMessage(msg);        }    }).start();}private static class CopyFileHandler extends Handler {    WeakReference<AppStartActivity> mActivity;    public CopyFileHandler(AppStartActivity activity) {        mActivity = new WeakReference<>(activity);    }    public void handleMessage(Message msg) {        final AppStartActivity activity = mActivity.get();       //handle you message here!    }}
Why is memory leakage?

So why not this cause memory leakage?
This is related to several keywords: internal class, Handler message loop, and Java garbage collection mechanism.
It should be emphasized that not every time Handler is used, it will lead to memory leakage. There is a certain probability that a specific condition must be met to cause leakage.
An internal class has a reference pointing to an external class.
The garbage collection mechanism stipulates that when the reference count of an object in the memory is 0, it will be recycled.
Handler acts as the asynchronous message processing mechanism on Android (well, I mostly use worker thread to synchronize with the UI thread). It works with logoff and MessageQueue. To put it simply, we need to maintain a loose to process MessageQueue ). Each cycle extracts a Message from MessageQueue, and calls back the corresponding Message processing function.

If, I mean, if there are unprocessed messages in the loop body (Message Queuing), then Handler will always exist, then the external class of Handler (usually Activity) so that the external class cannot be reclaimed. Many people will encounter the reason why the onDestroy method of the activity has not been executed.

Try another solution

The warning description mentions Handler's use of logoff or MessageQueue in worker thread. I tried it for your reference.

    private Handler testHandler;    private Thread mThread = new Thread() {        public void run() {            Log.d(TAG,"mThread run");            Looper.prepare();            testHandler = new Handler() {                public void handleMessage(Message msg) {                    Log.d("TAG", "worker thread:"+Thread.currentThread().getName());                    switch (msg.what) {                        //handle message here                    }                }            };            Looper.loop();        }    };    //start thread here    if(Thread.State.NEW == mThread.getState()) {        Log.d(TAG, "mThread name: " + mThread.getName());        mThread.start();    }    //send message here    testHandler.sendEmptyMessage(1);

Refer:
Http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler
Http://m.blog.csdn.net/blog/wurensen/41907663
Http://blog.csdn.net/lmj623565791/article/details/38377229

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.