Android handle 弱引用防止内存泄露

来源:互联网 发布:搞笑的网络剧排行榜 编辑:程序博客网 时间:2024/05/03 17:33

private Handler handler;


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

     handler=new ViewHandler(this);

}

必须声明成static

static class ViewHandler extends Handler {
        
        WeakReference<PrivateShareActivity> thisLayout;
        
        ViewHandler(PrivateShareActivity layout){
            thisLayout = new WeakReference<PrivateShareActivity>(layout);
        }
        
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            PrivateShareActivity theLayout = thisLayout.get();
            if (theLayout == null) {
                return;
            }
            switch (msg.what) {
            case DOWN_ZIP_FAIL:
                theLayout.imageView.setVisibility(View.VISIBLE);
                theLayout.downZipLayout.setVisibility(View.GONE);
                break;
            case DOWN_ZIP_START:
                theLayout.imageView.setVisibility(View.GONE);
                theLayout.downZipLayout.setVisibility(View.VISIBLE);
                break;
            default:
                break;
            }

        }
    };

0 0
原创粉丝点击