1.android里每个服务启动时context到底从哪里来的呢????以mountservice的context为例
在SystemServer.java的run函数中有如下代码
context = ActivityManagerService.main(factoryTest);
......
if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
try {
/*
* NotificationManagerService is dependant on MountService,
* (for media / usb notifications) so we must start MountService first.
*/
Slog.i(TAG, "Mount Service");
mountService = new MountService(context);
ServiceManager.addService("mount", mountService);
} catch (Throwable e) {
reportWtf("starting Mount Service", e);
}
}
由此可知,由systemserver启动的服务的context都来自ActivityManagerService
ActivityManagerService.java
public static final Context main(int factoryTest) {
......
ActivityThread at = ActivityThread.systemMain();
......
Context context = at.getSystemContext();
......
return context;
}
由上可知,该context是由ActivityThread 创建的
ActivityThread .java
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
ContextImpl context =
ContextImpl.createSystemContext(this);
LoadedApk info = new LoadedApk(this, "android", context, null,
CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
context.init(info, null, this);
context.getResources().updateConfiguration(
getConfiguration(), getDisplayMetricsLocked(
Display.DEFAULT_DISPLAY,
CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO));
mSystemContext = context;
//Slog.i(TAG, "Created system resources " + context.getResources()
// + ": " + context.getResources().getConfiguration());
}
}
return mSystemContext;
}
在ContextImpl .java中
static ContextImpl createSystemContext(ActivityThread mainThread) {
final ContextImpl context = new ContextImpl();
context.init(Resources.getSystem(), mainThread, Process.myUserHandle());
return context;
}
由此可知所有systemserver启动的服务的context对象实际为一个ContextImpl对象
即ServerThread::run<-ActivityManagerService.main<-ActivityThread::getSystemContext<-ContextImpl.createSystemContext
2.对于一个apk中的context一般直接指向这个activity本身,因为activity本身即继承自context