最近在继续iPhone业务的同时还需要重新拾起Android。在有些生疏的情况下,决定从Android源码中感悟一些Android的风格和方式。在学习源码的过程中也发现了一些通用的模式,希望通过一个系列的文章总结和分享下。
    代理模式为其他对象提供一种代理以控制对这个对象的访问。代理还分成远程代理、虚代理、保护代理和智能指针等。Android系统中利用AIDL定义一种远程服务时就需要用到代理模式。以StatusBarManager为例,其代理模式的类图如下:
Android和设计模式:代理模式
主要的实现代码如下:
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同真正的服务交互。

转载于:https://blog.51cto.com/bj007/649071

相关文章:

  • 2021-05-22
  • 2022-01-09
  • 2021-12-18
  • 2022-01-15
猜你喜欢
  • 2021-05-03
  • 2021-06-05
  • 2021-10-12
  • 2021-06-12
  • 2021-07-02
  • 2021-05-11
相关资源
相似解决方案