你的构造函数里面不是传入了一个上下文的对象吗?用它就行了啊。 Context是一个抽象对象,它的子类比较多,Activity就是它的子类,Service也是。 这样理解就很简单了:
一个APK进程只有一个Context: 这个Context就是ApplicationContext,从Context继承过来。
ApplicationContext可以看做是针对整个系统的全局处理接口,因为: 它负责和系统服务打交道 RPC通信由他通过那些XXXServiceManager和XXXService来处理。
其他一些模块,比如Activity,Service等,也是从Context继承而来的。 比如Acitivity在attach到主线程(ActivityThread)时,会用ApplicationContext来初始化这个Activity,这样就OK了。
比如Activity中StartService,调用过程如下: Activity.StartService (Activity继承自ContextWraper,实际会执行 ContextWraper中的) public ComponentName startService(Intent service) { return mBase.startService(service); }
这里面的mBase实际就是ApplicationContext
ApplicationContext中的实现如下: @Override public ComponentName startService(Intent service) { try { ComponentName cn = ActivityManagerNative.getDefault().startService( mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(getContentResolver())); if (cn != null && cn.getPackageName().equals("!")) { throw new SecurityException( "Not allowed to start service " + service + " without permission " + cn.getClassName()); } return cn; } catch (RemoteException e) { return null; } }
通过系统服务来做的。
总之:context就是将这些系统服务提供的功能,完美的包装起来了,其中的RPC过程,用户无需关心。好像这些功能就是在那,自己可以随便使用(要知道跨进程通信和调用,是非常难和麻烦的事情)。 |