美文网首页
Handler在Activity和Fragment中的内存泄露问

Handler在Activity和Fragment中的内存泄露问

作者: 飞天_shine | 来源:发表于2017-12-19 15:58 被阅读0次

    解决方法:将handler声明为static静态方法

    在activity中:

    private final MyHandler handler=new MyHandler(this);//在activity中声明handler

    private static class MyHandler extends Handler {

    private final WeakReference mActivityReference;

    MyHandler(Activity activity) {

    this.mActivityReference=new WeakReference<>(activity);

    }

    @Override

    public void handleMessage(Message msg) {

    super.handleMessage(msg);

    final MainActivity activity = (MainActivity)mActivityReference.get();//获取弱引用队列中的activity

    if(activity!=null){

    switch(msg.what) {//获取消息,更新UI

    }

    }

    }

    }

    //消息队列里面的消息移除

    @Override

    protected voidonDestroy() {

    super.onDestroy();

    _handler.removeCallbacksAndMessages(null);

    context=null;

    }


    在fragment中

    private final MyHandler handler=new MyHandler(this);//在activity中声明handler

    private static class MyHandler extends Handler {

    private final WeakReference mFragmentReference;

    MyHandler(Fragment fragment) {

    this.mFragmentReference=new WeakReference<>(fragment);

    }

    @Override

    public void handleMessage(Message msg) {

    super.handleMessage(msg);

    final MainFragment fragment= (MainFragment)mFragmentReference.get();

    if(fragment!=null){

    switch(msg.what) {//获取消息,更新UI

    }

    }

    }

    }

    //消息队列里面的消息移除

    @Override

    protected voidonDestroy() {

    super.onDestroy();

    _handler.removeCallbacksAndMessages(null);

    }

    相关文章

      网友评论

          本文标题:Handler在Activity和Fragment中的内存泄露问

          本文链接:https://www.haomeiwen.com/subject/lwxiwxtx.html