此处理程序 class 应该是静态的,否则可能会发生泄漏 (null)

This Handler class should be static or leaks may occur (null)

This Handler class should be static or leaks may occur (null)

这里的 'class' 这条消息是指 'MyActivity' 吗,因为 Handler 是一个对象,我确实将其声明为静态的。我应该忽略它还是应该添加一些东西,比如 'MyActivity' 声明中的某处 'static' (我试过这个但出错了)。我注意到 'WeakReference' 通常被建议用于此 lint 警告。

public class MyActivity extends Activity{
...
static Handler handler;
...
handler = new Handler()
  {
    public void handleMessage(Message msg) {

since Handler is an object and i did declare it static

您将 数据成员 声明为静态。但是,您使用的是匿名内部 class,因此 Handler 的子 class 不是 static

而不是:

  handler = new Handler() {
    public void handleMessage(Message msg) {
      // do cool stuff
    }
  };

使用:

handler=new MyVeryOwnHandler();

其中 MyVeryOwnHandler 是常规 Java class 或 static 内部 class:

private static class MyVeryOwnHandler extends Handler {
  public void handleMessage(Message msg) {
      // do cool stuff
  }
};

注意错误是class需要static;它并没有说 object 需要是 static.

为了避免泄漏,我还迁移到了静态嵌套 class。 Android Studio 的解释是这样说的,可能会有帮助:

Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.

在迁移之前,我按照 developer.android.com 的建议使用了 Looper 线程的实现,这最终导致了警告。 *划痕

  class LooperThread extends Thread {
  public Handler mHandler;

  public void run() {
      Looper.prepare();

      mHandler = new Handler() {
          public void handleMessage(Message msg) {
              // process incoming messages here
          }
      };

      Looper.loop();
  }  
 }