Memory leakage caused by internal Handler class and This Handler class shocould be static or lea

Source: Internet
Author: User

We can find this change:

public class MainActivity extends Activity {     private  Handler mHandler = newHandler() {        @Override        public void handleMessage(Message msg) {            //TODO handle message...        }     };     @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 run the Android Lint tool to warn about memory leakage: This Handler class shocould be static or leaks might occur.

To modify this issue, you only need to define the Handler class as static as prompted by Lint, and then use WeakReference to keep external Activity objects.

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


Therefore, when you use an internal class in an Activity, you must always consider whether you can control the lifecycle of the internal class. If not, you 'd better define it as a static internal class.



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.