【问题标题】:"Handler class should be static or leaks might occur" - Handler has references to main activity variables“处理程序类应该是静态的,否则可能会发生泄漏” - 处理程序具有对主要活动变量的引用
【发布时间】:2013-02-26 20:42:27
【问题描述】:

Android:我在我的活动中定义了一个处理程序类,我收到警告“处理程序类应该是静态的,否则可能会发生泄漏”,代码如下:

    Handler messageHandler = new Handler() {
      // @Override 
      public void handleMessage(Message msg) {
        try {
            ... accessing variables defined at the activity level
            ... doing something very important
        }
        super.handleMessage(msg)
      }
    }

但是,问题是我的消息处理程序有对主要活动变量的引用,所以我不能使它成为静态的。在我的情况下,我怎样才能摆脱该警告(以正确的方式)?

【问题讨论】:

    标签: variables android-activity reference static handler


    【解决方案1】:

    改变

    Handler messageHandler = new Handler() {
          // @Override 
          public void handleMessage(Message msg) {
            try {
                ... accessing variables defined at the activity level
                ... doing something very important
            }
          }
        }
    

    Handler mIncomingHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
        }
    });
    

    参考: This Handler class should be static or leaks might occur: IncomingHandler

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 2013-05-20
      • 2017-11-02
      • 2012-07-09
      相关资源
      最近更新 更多