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:
- 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.
- 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?
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 “structin 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.