Alex L.
Alex L.

Reputation: 57

"Handler class should be static or leaks might occur" - Handler has references to main activity variables

Android: i have a Handler class defined inside my activity and i get the warning "Handler class should be static or leaks might occur" with the following code:

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

However, the problem is that my message Handler has references to main activity variables, so i cannot make it static. How in my case can i get rid of that warning (in correct manner)?

Upvotes: 3

Views: 1836

Answers (1)

whutdyp
whutdyp

Reputation: 121

Change

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

To

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

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

Upvotes: 7

Related Questions