2

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)
      }
    }

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

4

1 回答 1

6

改变

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) {
    }
});

参考: 这个 Handler 类应该是静态的,否则可能会发生泄漏:IncomingHandler

于 2013-04-22T02:27:09.427 回答