Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android 中handler的HandlerLeak问题

原因:Handler在Android中用于消息的发送与异步处理,常常在Activity中作为一个匿名内部类来定义,此时Handler会隐式地持有一个外部类对象(通常是一个Activity)的引用。当Activity已经被用户关闭时,由于Handler持有Activity的引用造成Activity无法被GC回收,这样容易造成内存泄露。 正确的做法是将其定义成一个静态内部类(此时不会持有外部类对象的引用),在构造方法中传入Activity并对Activity对象增加一个弱引用,这样Activity被用户关闭之后,即便异步消息还未处理完毕,Activity也能够被GC回收,从而避免了内存泄露。

    public static class MyHandler extends Handler {
        private WeakReference<Activity> reference;
        
        public MyHandler(Activity activity) {
            reference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            if (reference.get() != null) {
                switch (msg.what) {
                case 0:
                    // do something...
                    break;
                default:
                    // do something...
                    break;
                }
            }
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment