美文网首页
Android: This Handler class shou

Android: This Handler class shou

作者: hello_math | 来源:发表于2017-02-16 10:51 被阅读149次

    0x00

    private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0: mTextView.setText("msg received"); break; } } };

    以往我习惯这样改变Android的UI,但是Android Studio Warning:
    This Handler class should be static or leaks might occur.

    0x01

    原因比较简单,msg发送的时候有一个delayed参数,如果在delayed参数以内该activity被destory了,但是mHandler还持有mContext等待接收消息,所以会引发内存泄漏。

    0x02

    solve idea:

    private final MyHandler mHandler = new MyHandler(this); private static class MyHandler extends Handler { private final WeakReference<VideoFragment> mVideoFragment; public MyHandler(VideoFragment m) { mVideoFragment = new WeakReference<VideoFragment>(m); } @Override public void handleMessage(Message msg) { VideoFragment m = mVideoFragment.get(); if (m != null) { switch (msg.what) { case 0: m.mTextView.setText("msg received"); break; default:break; } } }}

    相关文章

      网友评论

          本文标题:Android: This Handler class shou

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