考慮一個相當基本的服務:它對服務中的消息處理程序是否靜態有多重要?
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;
}
}
}
}
}
現在,如果我開發這個與皮棉運行Eclipse,我有兩個選擇之間做出選擇目前:
- 的如上所示的代碼將在私有最終類IncomingMessageHandler行上發出警告,聲明它應該作爲靜態進行decalared以確保所有內容在運行時都能正常工作。
- 如果我作出這樣的類(IncomingMessageHandler)一成不變的,它不能再訪問數據和功能的整體水平(KeepANumberService),這是一種痛苦(在某些情況下可能是不可能的?)代碼。
那麼,如何重要的是它使信息處理靜態的?爲什麼?
就發現有一個非常完整的答案類似的問題,包括參考,甚至更充分的說明其它地方:http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-可能-發生-incominghandler –