考虑一个相当基本的服务:
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;
}
}
}
}
}
现在,如果我在运行 lint 的 eclipse 中开发它,我目前可以在两个选项之间进行选择:
- 上面的代码将在私有 final 类 IncomingMessageHandler 行上有一个警告,说它应该被声明为静态,以确保一切在运行时正常工作。
- 如果我将该类 (IncomingMessageHandler) 设为静态,它就不能再访问整个类 (KeepANumberService) 中的数据和函数,这对编码来说是一种痛苦(在某些情况下可能是不可能的?)。
那么,使消息处理程序静态化有多重要?为什么?