0

Consider a fairly basic service:

class KeepANumberService extends Service {
    // The codes used in incoming messages
    final static int REQUEST_SET_NUMBER = 0;
    final static int REQUEST_GET_NUMBER = 1;

    // The information this service works with internally
    int numberToKeep = 0;

    // The handler for incoming messages
    private IncomingMessageHandler incomingMessageHandler = new IncomingMessageHandler();

    // Start up and close down stuff
    < Insert standard start up and close down code OnCreate, OnBind etc etc here >

    void returnNumber(Messenger destination) {
         Message msg = <construct message with numberTo>;
         destination.send(msg);
    }

    // Handler that receives messages from the thread
    private class IncomingMessageHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case REQUEST_SET_NUMBER:
                numberToKeep = msg.whatever; // get data from wherever it's hidden in the msg
                break;
            case REQUEST_GET_NUMBER:
                returnNumber(msg.replyTo);
                break;
            } 
          }
      }
  }

}

Now, if I am developing this in eclipse with lint running, I have a choice between two options at present:

  1. The code as above will have a warning on the private final class IncomingMessageHandler line saying that it should be decalared as a static to ensure everything works at run time.
  2. If I make that class (IncomingMessageHandler) static, it can no longer access data and functions in the overall class (KeepANumberService), which is a pain (possibly impossible in some cases?) to code.

So, how important is it to make the message handler static? And why?

Neil Townsend
  • 6,024
  • 5
  • 35
  • 52
  • Just spotted a similar question with a very complete answer, including reference to even fuller explanation elsewhere: http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler – Neil Townsend Nov 26 '12 at 11:15

1 Answers1

1

The keyword static, when used on inner class definitions, says that the inner class does not require a reference to the outer class. Usually you do this if the inner class is a "data container" (think "struct in C"). In your case, your inner class is not a data container, it is simply a private inner class that has methods and requires access to the member variables of the outer class. So there is absolutely no reason to declare this class static. That would be counterproductive.

Looking at your code I have no idea why you get a warning to declare this class static. Just ignore it.

David Wasser
  • 93,459
  • 16
  • 209
  • 274