最近在继续iPhone
业务的同时还须要从新拾起Android
。在有些生疏的状况下,决定从Android
源码中感悟一些Android
的风格和方式。在学习源码的过程当中也发现了一些通用的模式,但愿经过一个系列的文章总结和分享下。
代理模式为其余对象提供一种代理以控制对这个对象的访问。代理还分红远程代理、虚代理、保护代理和智能指针等。Android系统中利用AIDL定义一种远程服务时就须要用到代理模式。以StatusBarManager为例,其代理模式的类图以下:
主要的实现代码以下:
public class StatusBarManager {
......
private Context mContext;
private IStatusBarService mService;
private IBinder mToken = new Binder();
StatusBarManager(Context context) {
mContext = context;
mService = IStatusBarService.Stub.asInterface(
ServiceManager.getService(Context.STATUS_BAR_SERVICE));
}
public void disable(int what) {
try {
mService.disable(what, mToken, mContext.getPackageName());
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void expand() {
try {
mService.expand();
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void collapse() {
try {
mService.collapse();
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void setIcon(String slot, int iconId, int iconLevel) {
try {
mService.setIcon(slot, mContext.getPackageName(), iconId, iconLevel);
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void removeIcon(String slot) {
try {
mService.removeIcon(slot);
} catch (RemoteException ex) {
// system process is dead anyway.
throw new RuntimeException(ex);
}
}
public void setIconVisibility(String slot, boolean visible) { try { mService.setIconVisibility(slot, visible); } catch (RemoteException ex) { // system process is dead anyway. throw new RuntimeException(ex); } } } 其中做为代理的StatusBarManager经过 IStatusBarService.Stub.asInterface(ServiceManager.getService(Context.STATUS_BAR_SERVICE))获取到了远程服务,用户经过StatusBarManager同真正的服务交互。