This handler class must be static or it might leak (null)

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

      

Is the "class" this post a reference to "MyActivity" here since the Handler is an object and I was declaring it static. Should I ignore it or is there something I should add like "static" somewhere in the "MyActivity" declaration (I've tried this and got errors). I notice that "WeakReference" is often suggested for this warning.

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

      

+3


source to share


2 answers


since Handler is an object and I have declared it static

You have declared the item to be static. However, you are using an anonymous inner class and therefore your subclass is Handler

not static

.

Instead:

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

      

using:



handler=new MyVeryOwnHandler();

      

where MyVeryOwnHandler

is either a regular Java class or an inner class static

:

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

      

Note that the error is that the class must be static

; it does not say that the object should be static

.

+22


source


To avoid leaks, I also switched to a static nested class. The explanation from Android Studio says this, it might help:

Since this handler is declared as an inner class, it can outer class from garbage collection. If the handler uses a Looper or MessageQueue for a thread other than the main thread, then the problem does not occur. If the handler uses the Looper or MessageQueue of the main thread, you need to correct the Handler declaration as follows: Declare the handler as a static class; In the outer class, create an instance of the WeakReference for the outer class and pass that object to your handler when instantiating the handler; Make all references to members of the outer class using a WeakReference object.



Before porting, I used the Looper thread implementation as suggested by developer.android.com , which results in a warning at the end. * Scratch

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

      

+3


source







All Articles