赞
踩
======
binder是进程间通信的一种方式。在操作系统中,分为内核空间和用户空间,每个app都运行在自己的用户空间,binder机制底层正是两个app进程通过共享内核内存区域实现的;具体实现不做深入分析;
在binder机制中,进行进程通信的两方,可分别称他们为Cient进程和Server进程;Cient进程和Server进程是由具体场景而定的,一个进程即可以是Cient进程,也可以是Server进程。
ServiceManager负责把Binder Server注册到一个容器中,这样当有Client进程想与Server进程通信时,ServiceManager就可以从查找表中找到Binder Server,并返回Binder Server的代理对象给Client进程。
ActivityManagerService是一个系统服务进程,四大组件的启动方式都是通过binder的方式与ActivityManagerService通信完成的;
ActivityManagerService将自己注册到ServiceManager的代码如下(本文分析基于android-29源码):
public class ActivityManagerService extends IActivityManager.Stub {
public void setSystemProcess() {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
}
}
注册完成之后,其他进程就可通过如下方式获得ActivityManagerService的代理:
public class ActivityManager {
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton IActivityManagerSingleton =
new Singleton() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
}
以上代码,可以看出ActivityManager封装了对ActivityManagerService的调用,通过ActivityManager.gerService()即可获得对ActivityManagerService的调用。
ActivityThread就是UI线程,是在APP启动时创建的;它包含一个static的main()方法如下所示(后面会详细分析):
public final class ActivityThread{
// 后面会重点分析
Instrumentation mInstrumentation;
public static void main(String[] args) {
// 省略部分代码…
Looper.prepareMainLooper();
// …
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
// …
Looper.loop();
}
private void attach(boolean system, long startSeq) {
mInstrumentation = new Instrumentation();
// …
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
}
}
ApplicationThread是ActivityThread的内部类,并不是一个线程,可用来代表当前APP进程(可能这就是它叫Thread的原因吧),由以下代码可分析出app间进程通信时,获得另一个app进程也是通过binder来获取其代理实现的;
private class ApplicationThread extends IApplicationThread.Stub {
// 省略部分代码…
}
instrumentation
英 [ˌɪnstrəmenˈteɪʃn] 美 [ˌɪnstrəmenˈteɪʃn]
n.(一套)仪器,仪表;器乐谱写
Instrumentation源码解释如下:
/**
可以大概理解为所有与application有关的调用都会通过Instrumentation这样一个仪器来方便地观察到;换句话说就是,所有有关application的调用实际上都会通过Instrumentation;看一下其源码就可以看到它里面完成了许多功能:
public class Instrumentation {
private ActivityThread mThread = null;
private MessageQueue mMessageQueue = null;
private List mActivityMonitors;
public Application newApplication(ClassLoader cl, String className, Context context) {}
public Activity newActivity(ClassLoader cl, String className,
Intent intent) {}
public void callActivityOnNewIntent(Activity activity, Intent intent) {}
public ActivityResult execStartActivity(){}
}
例如App1要启动App2的一个Activity;Activity启动流程分析如下:
public class SampleActivity1 {
public void onClick() {
Intent intent = getPackageManager().getLaunchIntentForPackage(“com.app2.sample”);
startActivity(intent);
}
}
public class Activity {
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
public void startActivity(Intent intent, @Nullable Bundle options) {
// …
startActivityForResult(intent, -1);
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
// 省略部分代码…
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
}
}
}
可以看到,Activity的startActivity最终都调用到了Instrumentation里面;
继续分析Instrumentation的execStartActivity()方法:
public class Instrumentation {
/**
可以看到,又继续调用到了ActivityTaskManager.getService().startActivity()里面。
ps. 在android-28源码中是调用到了ActivityManager.getService().startActivity()里面,更老版本android源码中是调用了ActivityManagerNative.getDefault(),原理都类似,都是调用返回一个代理,最终到了系统进程去执行后续调起逻辑。
@SystemService(Context.ACTIVITY_TASK_SERVICE)
public class ActivityTaskManager {
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
private static final Singleton IActivityTaskManagerSingleton =
new Singleton() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
}
可以看出,ActivityTaskManager.getService()调用得到IBinder的proxy继续执行后续代码,这样就就调用到了系统进程里面继续执行;ActivityTaskManager是系统启动期间就注册的一个binder service,其注册代码如下:
@SystemApi
public final class SystemServiceRegistry {
static {
registerService(Context.ACTIVITY_TASK_SERVICE, ActivityTaskManager.class,
new CachedServiceFetcher() {
@Override
public ActivityTaskManager createService(ContextImpl ctx) {
return new ActivityTaskManager(
ctx.getOuterContext(), ctx.mMainThread.getHandler());
}});
}
接下来继续分析系统进程中startActivity()的执行步骤;
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
boolean validateIncomingUser) {
// 省略部分代码…
// getActivityStartController().obtainStarter返回一个ActivityStarter对象,下面继续分析ActivityStarter
return getActivityStartController().obtainStarter(intent, “startActivityAsUser”)
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();
}
}
ActivityStarter负责处理intent中flag、启动模式等参数;
class ActivityStarter {
int execute() {
try {
// …
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
mRequest.outActivity, mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup,
mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
} finally {
onExecutionComplete();
}
}
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
int result = START_CANCELED;
final ActivityStack startedActivityStack;
try {
mService.mWindowManager.deferSurfaceLayout();
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
}
// …
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
// …
mRootActivityContainer.resumeFocusedStacksTopActivities();
}
}
接下里继续到RootActivityContainer;
/**
ActivityStack负责管理activity栈和activity的状态,包括根据activity栈的状态决定如何管理activity等,当然activity的启动也是由它来继续完成;
/**
boolean result = false;
try {
// Protect against recursion.
mInResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
}
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
// …
if (next.attachedToProcess()) {
if (nextNext != next) {
// Do over!
mStackSupervisor.scheduleResumeTopActivities();
}
} else {
// Whoops, need to restart this activity!
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
}
}
// TODO: This class has become a dumping ground. Let’s
// - Move things relating to the hierarchy to RootWindowContainer
// - Move things relating to activity life cycles to maybe a new class called ActivityLifeCycler
// - Move interface things to ActivityTaskManagerService.
// - All other little things to other files.
// 看样子这部分代码后面也会被RootWindowContainer里面,后面Android源码分析可能要重点分析这个类了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。