前面說過MessageHandle機制,它保證了android上層代碼線程間的通訊。
訊息註冊機制更加豐富了MessageHandle的流程,它把過程嚴格階段化了,分成訊息註冊和通知訊息處理兩個部分,讓人一目瞭然。
訊息註冊機制的總體思想是:一個對象中開闢一個空間用於存放Message,當調用regist方法時將Message存放進去,當其調用notify方法時將所有Message取出並發送到MessageQueue中等待處理。
下面是類比程式,提供Registrant,RegistrantList,AsyncResult,MiddleUser類
package com.zte.liu.registermessage;
public class AsyncResult {
MessageParmeters parmList;
Object result;
Throwable exception;
public Throwable getException() {
return exception; www.2cto.com
}
public void setException(Throwable exception) {
this.exception = exception;
}
AsyncResult(Object result, Throwable exception){
parmList = new MessageParmeters();
this.result = result;
this.exception = exception;
}
public MessageParmeters getMessageParms(){
return parmList;
}
public Object getResult(){
return result;
}
public void setResult(Object result){
this.result = result;
}
public AsyncResult refresh(Object parm){
parmList.refresh(parm);
return this;
}
}
package com.zte.liu.registermessage;
import com.zte.liu.messagehandler.Handler;
public class MiddleUser {
RegistrantList registrantList = new RegistrantList();
public void registForReason(Handler handler, int what, Object firstParms){
registrantList.add(handler, what, firstParms);
}
public void notifyRegistrant(Object secondParms, Throwable exception){
registrantList.notifyRegistrantList(secondParms, exception);
}
public void unRegistForReason(int what){
registrantList.remove(what);
}
}
package com.zte.liu.registermessage;
import com.zte.liu.messagehandler.Handler;
import com.zte.liu.messagehandler.Message;
public class Registrant {
private Message msg = null;
Registrant(Handler handler, int what, Object firstParms){
msg = new Message(what, handler, new AsyncResult(null, null).refresh(firstParms));
}
public void notifyRegistrant(Object secondParms, Throwable exception){
if(msg == null){
return;
}
AsyncResult asyncResult = (AsyncResult)msg.getObj();
asyncResult.refresh(secondParms).setException(exception);
msg.sendToTarget();
}
public Message getMessage(){
return msg;
}
}
package com.zte.liu.registermessage;
import java.util.ArrayList;
import com.zte.liu.messagehandler.Handler;
public class RegistrantList {
private ArrayList<Registrant> registrantList = new ArrayList<Registrant>();
public synchronized void add(Handler handler, int what, Object firstParms){
Registrant registrant = new Registrant(handler, what, firstParms);
registrantList.add(registrant);
}
public synchronized void remove(int what){
for(int i=0; i<registrantList.size(); i++){
if(((Registrant)registrantList.get(i)).getMessage().getId() == what){
registrantList.remove(i);
}
}
}
public synchronized void notifyRegistrantList(Object secondParms, Throwable exception){
for(int i=0; i<registrantList.size(); i++){
Registrant registrant = (Registrant)registrantList.get(i);
registrant.notifyRegistrant(secondParms, exception);
}
}
}
摘自:liuyangsyouxiang的專欄