从点击桌面APP图标,到APP界面显示的全流程(一)-基于Android 13(Android T)

  • 从点击桌面APP图标,到APP界面显现的全流程(一)-依据Android 13(Android T)
  • 从点击桌面APP图标,到APP界面显现的全流程(二)-依据Android 13(Android T)

注:

  • 本文依据 Android 13 (Android T) 源码剖析

    准确说是依据 android-13.0.0_r31,或许现在最新的master分支

  • 本文解说内容: 从点击桌面APP图标,到APP界面显现的悉数流程

  • 或许说是“Android 图形显现体系”

  • 本文着重于 SurfaceFlinger 相关内容

  • 本文致力于对复杂的Android源码浓缩进一篇文章,有一个纵观大局的认知(对安卓全图开个小个地图)。

  • 流程图涉及到十几个目标时,会比较混乱,大段贴代码的形式,会导致文章很有个大局认知

    因而本文测验调用栈+注释的写作形式。

    由于界面宽度问题,可以修改Typora的主题装备宽度为1400px

    修改 C:\Users\xxxxx\AppData\Roaming\Typora\themes\github.css 中的 max-width: 1400px;

  • 本文尽可能的把 IMS、AMS、Zygote、APP、WMS、SurfaceFlinger 进程以及线程之间的调用无缝衔接。

  • 本文从上到下,基本是依照代码履行的时刻顺序书写

  • 全文2.5万词,17万字符,3200行,现在1.0版别,文章或有部分错误,或待验证内容,以及部分细节今后再慢慢更新。

一、点击桌面App图标事情分发

  • systemserver进程发动时,会发动 inputflinger 服务: native层的 InputManager

  • InputManager 发动时,发动 InputDispatcher 线程和 InputReader 线程

  • InputReader 线程循环调用 EventHub 的 getEvents 办法,linux设备节点/dev/input文件夹下的event读取事情

  • InputReader 读取到事情后,放到 InputDispatcher.mInboundQueue 行列中,并告诉 InputDispatcher 线程读取数据

  • InputDispatcher 线程唤醒后,从 mInboundQueue 行列中取出事情,按事情类型进行分发。

  • 关于触屏事情,会寻觅屏幕触控事情的焦点窗口,找到后把事情放入 Connection.outboundQueue 行列中

    • Connection是在窗口增加时在 WindowState.openInputChannel 调用进程中创立的,
    • 一个 Connection有一个服务端的InputChannel,一个InputChannel有一个socketpair服务端socket的fd,
    • 一起 socketpair客户端的fd会被发送到App进程,并参加epoll监听
    • 因而Connection就代表同App端的socket衔接(或许说是管道)
  • 终究经过 Connection 中的 socket 把事情发送到 App

InputDispatcher分发流程

InputDispatcher::start();// 这个start是SystemServer进程发动进程调用的
//  发动线程。循环履行 dispatchOnce()
|	mThread = std::make_unique<InputThread>( "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
|-->InputDispatcher::dispatchOnce();
    |	dispatchOnceInnerLocked(&nextWakeupTime);
		//	取出行列第一个数据, mPendingEvent 作为成员变量,表明待处理事情,一次循环处理一个待处理事情
		|	mPendingEvent = mInboundQueue.front();
		//	取出后,移除第一个数据
		|	mInboundQueue.pop_front();
		//	依据事情类别,分别调用不同的事情分发函数,比方,按键事情调用 dispatchKeyLocked
		|	switch (mPendingEvent->type) 
            //	以屏幕触控事情为例
            |	case EventEntry::Type::MOTION:
				|	// 分发屏幕触控事情 
				|	done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
						//	寻觅屏幕触控事情的焦点窗口,把所有接纳当时输入事情的窗口的InputChannel封装到InputTarget,并增加到调集inputTargets
						|	findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
						|	dispatchEventLocked(currentTime, entry, inputTargets);
							//	遍历调集 inputTargets
							|	for (const InputTarget& inputTarget : inputTargets) 
                                // 依据 token 拿到 Connection 【见:addToDisplayAsUser 章节】
        						// 从map类型数据 mConnectionsByToken 依据key InputChannel.mToken 查找 Connection
        						// std::unordered_map<sp<IBinder>, sp<Connection>> mConnectionsByToken
        						// mConnectionsByToken 中的数据是 createInputChannel 是增加的
        						// createInputChannel 是增加窗口时在 WindowState.openInputChannel 调用进程中调用。
                                // 一个 Connection有一个服务端的InputChannel,一个InputChannel有一个socketpair服务端socket的fd
                                // 因而Connection就代表同App端的socket衔接(或许说是管道)
                                |	sp<Connection> connection = getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
								|	prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
									| enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
									  | enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, FLAG_DISPATCH_AS_IS);
										//	把需求分发的事情参加到关于窗口的Connection.outboundQueue行列中
										|	connection->outboundQueue.push_back(dispatchEntry.release());
									  // 开端循环分发事情	
									  | startDispatchCycleLocked(currentTime, connection);
										// outboundQueue 行列不为空就一向循环处理
										| while (!connection->outboundQueue.empty())
                                            | connection->inputPublisher.publishMotionEvent(...)
                                            	| mChannel->sendMessage(&msg);
													// 经过socket把事情发生给客户端
													|	::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
                                            // 删去outboundQueue行列中已发送的事情
                                            | connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
                                                    connection->outboundQueue.end(),
                                                    dispatchEntry));
											// 已发送的事情参加Connection的 waitQueue
											// App端处理完事情后,会回调回来删去waitQueue中的事情
											// AMR 查看时,waitQueue 中的事情超时未回调,会触发ANR
											| connection->waitQueue.push_back(dispatchEntry);
	//	处理ANR
	|	const nsecs_t nextAnrCheck = processAnrsLocked();
	|	mLooper->pollOnce(timeoutMillis);

App进程事情分发

  • looper epoll监听 SocketPair 的fd 【这个fd的来历见:addToDisplayAsUser 章节】

  • socket来数据后,回调 NativeInputEventReceiver::handleEvent

    • android::NativeInputEventReceiver.consumeEvent

    • native 反射调用Java层 InputEventReceiver.deliverInputEvent

    • WindowInputEventReceiver.onInputEvent

    • ViewRootImpl.enqueueInputEvent//履行入队操作—PendingInputEventQueue

    • doProcessInputEvents()

    • deliverInputEvent(q);//这儿会在systrace显现 deliverInputEvent块

      • 经过若干步骤后

      • mView.dispatchPointerEvent(event);//进入view的事情分发流程

        然后 view 再处理各自的touch事情。

        比方ScrollView,在touch事情中,会调整view的坐标,然后调用 invalidate 函数,函数终究会调用 requestNextVsync 触发 vsync ,vsync 回调doframe中绘制流程中,ScrollView依据新的坐标绘制界面,然后就看到了界面滚动。

事情分发到桌面图标的view后,view自身的点击事情中调用 startActivity 发动App。

二、APP创立进程

App到systemserver进程

Activity 的 startActivity 函数会调用到 ActivityTaskManagerService 的 startActivityAsUser 或许其他几个 start 办法

  • ActivityTaskManagerService.startActivityAsUser

  • —>ActivityStarter.execute

  • —>ActivityStarter.executeRequest

    • 内部创立ActivityRecord : ActivityRecord r = new ActivityRecord.Builder(mService)
      • ActivityRecord 承继 WindowToken
      • Android 12 结构函数中 appToken = new Token
        • Token extends IApplicationToken.Stub
      • token,这个东西Android 11,Android12,Android13 这儿的代码都不相同。
      • Android 13 Token extends Binder
        • ActivityRecord 没有 appToken 变量了,也是new Token,然后传递到 父类 WindowToken 中
      • 由于结构函数中传递的DisplayContent为null,新创立的 ActivityRecord 还不会参加 DisplayContent 的HashMap目标 mTokenMap
  • —>ActivityStarter.startActivityUnchecked

  • —>ActivityStarter.startActivityInner

    • setNewTask–>addOrReparentStartingActivity(task, “setTaskFromReuseOrCreateNewTask”); 把 ActivityRecord 增加到使命栈
      • 给 ActivityRecord 增加 parent : parent.addChild(mStartActivity); ActivityRecord.getTask 回来的便是这个 targetTask
      • addOrReparentStartingActivity 终究会把 ActivityRecord 参加到 DisplayContent .mTokenMap
    • mTargetRootTask.startActivityLocked
      • 判断当时 activity 是否需求为其新建 Task,将 ActivityRecord 参加到对应的 Task 栈顶中
      • ActivityRecord.showStartingWindow 发动过度界面
    • mTargetRootTask.moveToFront
    • RootWindowContainer.resumeFocusedTasksTopActivities===>转Task.resumeFocusedTasksTopActivities
    • mSupervisor.mRecentTasks.add(mStartActivity.getTask())
    • 其他使命栈相关的处理
  • —> Task.resumeFocusedTasksTopActivities

  • —> Task.resumeTopActivityUncheckedLocked

  • —> Task.resumeTopActivityInnerLocked // 这儿写是的Android12的流程,Android 13 这儿不相同了

    • ActivityRecord next = topRunningActivity(true /* focusableOnly */);
    • —>假如有相关的进程,则直接调度生命周期:mAtmService.getLifecycleManager().scheduleTransaction(transaction);
    • —>假如是新的activity【mTaskSupervisor.startSpecificActivity(next, true, true)】,业务增加 LaunchActivityItem Callback,用于app进程创立activity。假如没有进程还会创立进程
  • —>ActivityTaskSupervisor.startSpecificActivity

    • —> 假如已有进程调用 realStartActivityLocked
    • —>没有进程,创立进程流程:mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? “top-activity” : “activity”);
  • –>ATMS.startProcessAsync

    • startProcessAsync 只是把使命post给AMS,调用 AMS.startProcess
  • –>ActivityManagerInternal.startProcess

    • ActivityManagerInternal.startProcess 是个笼统办法,实现是 ActivityManagerService.LocalService.startProcess
  • –>ActivityManagerService.LocalService.startProcessLocked

    • 创立 HostingRecord ,并作为参数传给下一步
    • HostingRecord .mHostingZygote 特点用于选择 zygote 类型
    • HostingRecord 结构函数未传入 hostingZygote 参数,运用默认的 REGULAR_ZYGOTE ,即惯例孵化器
  • ActivityManagerService.startProcessLocked 没啥内容,直接调用 ProcessList.startProcessLocked

  • –>16参数的ProcessList.startProcessLocked

    • 处理 badProcess,接连溃散超越2次会变成badProcess,后台禁止发动badProcess
    • 处理隔离进程
    • 处理不同App在同一个进程状况,App正在发动状况
      • 正在发动的话,直接回来
    • 处理App已经逝世,可是逝世告诉还未到来的状况
    • 处理体系还未发动完结状况,先把App存起来,之后处理
  • –>4参数的ProcessList.startProcessLocked 直接转发到6参数的 startProcessLocked

  • –>6参数的ProcessList.startProcessLocked 代码许多主要是设置发动参数

    • 进程正在发动中,回来
    • 记载发动开端的时刻
    • 整理参加的 逝世告诉信息
    • 整理mProcessesOnHold用于保存那些在体系还没有准备好就提早恳求发动的ProcessRecord
    • 更新 Profiler 信息
    • 设置外存储挂载形式、设置App权限:gids
    • 处理 manifest中设置了android:debuggable 信息,增加debug发动参数
    • 设置 ABI、设置指令集、设置 selinux
    • 设置App进程的发动进口为 “android.app.ActivityThread
  • –>ProcessList.startProcess

    • 发动准备
    • 设置一些正在发动的标志
    • 异步发动和同步发动,默认运用异步发动
  • –>ProcessList.handleProcessStart 异步发动

    • 假如上一个App还没有逝世告诉,则延迟发动,延迟时刻最长默认 10 秒
    • 正常状况直接调用 ProcessList.startProcess
  • –>ProcessList.startProcess

    • 处理存储目录
    • 选择创立App进程的孵化器,由于HostingRecord .mHostingZygote 为 REGULAR_ZYGOTE ,因而调用 Process.start
  • –>Process.start 没啥内容,直接调用 ZygoteProcess.start

  • –>ZygoteProcess.start

    • 处理usap,usap启用的话,预创立APP进程,最大创立10个线程

    • Android 13 由特点 dalvik.vm.usap_pool_enabled 决定是否启用usap,这个特点默以为false

    • 之后调用 ZygoteProcess.startViaZygote

  • –>ZygoteProcess.startViaZygote 把参数封装成字符串

  • –>ZygoteProcess.zygoteSendArgsAndGetResult 处理一些字符串反常,并参加数据巨细

    • 调用 openZygoteSocketIfNeeded(abi) 衔接 ZygoteServer ,依据ABI确定衔接 zygote(zygote64) 仍是 zygote_secondary(zygote32)
  • –>ZygoteProcess.attemptZygoteSendArgsAndGetResult 写完socket,接着后读socket –>zygoteWriter.write(msgStr);
    –>运用socket 数据传输到 ZygoteServer

ZygoteServer进程

从Zygote发动讲起

ZygoteInit.main // Zygote 有两种发动办法,一种是发动system_server 一种发动App

  • main函数

    • 1、非懒加载状况下,预加载资源:jar,图形库,drawable、字体
    • 2、创立zygote进程的socket server服务端目标 ZygoteServer
    • 3、调用 ZygoteServer.runSelectLoop 进入死循环,等候 AMS 创立进程的socket音讯(也会处理其他音讯)
    • 4、调用 runSelectLoop 回来的 Runnable.run 办法
  • ZygoteServer.runSelectLoop

  • ZygoteServer.acceptCommandPeer // 得到一个恳求衔接封装目标ZygoteConnection

  • ZygoteConnection.processCommand //处理AMS客户端恳求

  • Zygote.forkSimpleApps // fork创立运用子进程,

    • ZygoteCommandBuffer.forkRepeatedly // 进入native层后,调用 fork()

    • Zygote.childMain

      • ZygoteInit.zygoteInit // 敞开 binder 音讯监听 ,设置反常处理函数
      • RuntimeInit.applicationInit
      • RuntimeInit.findStaticMain
        • return new MethodAndArgsCaller(m, argv);

MethodAndArgsCaller 目标不再承继Exception,只是承继Runnable,

MethodAndArgsCaller经过层层 return 后,回来 ZygoteInit.main ,

终究调用 MethodAndArgsCaller.run 办法 经过反射创立ActivityThread目标并调用其“main”进口办法。

ZygoteInit.main
ZygoteInit.main(String[] argv);
|	ZygoteServer zygoteServer = null;
|	Runnable caller;    
// 非懒加载状况下,预加载资源
|-->static void preload(TimingsTraceLog bootTimingsTraceLog);
	|	preloadClasses(); // 加载 /system/etc/preloaded-classes 
	//  加载非发动运用的类:
	//	/system/framework/android.hidl.base-V1.0-java.jar 
	//	/system/framework/android.hidl.manager-V1.0-java.jar
	//	/system/framework/android.test.base.jar
    |	cacheNonBootClasspathClassLoaders();
     /*
       com.android.internal.R.array.preloaded_drawables
       com.android.internal.R.array.preloaded_color_state_lists
       com.android.internal.R.array.preloaded_freeform_multi_window_drawables
      */
	|	preloadResources();
	// 预加载图形缓存map库
	// Gralloc4Mapper::preload();Gralloc3Mapper::preload();Gralloc2Mapper::preload();
	|	nativePreloadAppProcessHALs();
	/* GL driver 或许 Vulkan driver 预加载 */
	|	maybePreloadGraphicsDriver();
	//	加载同享库:libandroid.so libcompiler_rt.so libjnigraphics.so
	|	preloadSharedLibraries();
	//	TextView.preloadFontCache();  加载字体
	|	preloadTextResources();
	|	WebViewFactory.prepareWebViewInZygote();
// native层获取socket fd; 命名空间mount rootfs; selinux_android_seapp_context_init();
|	Zygote.initNativeState(isPrimaryZygote);
//假如是主Zygote,Zygote 64位,创立地址名为 zygote 的socket服务端,以及usap socket服务 usap_pool_primary
//假如是次Zygote,Zygote 32位,创立地址名为 zygote_secondary 的socket服务端,以及usap socket服务 usap_pool_secondary
|	zygoteServer = new ZygoteServer(isPrimaryZygote);
//	假如argv参数中有 "start-system-server" 则fork SystemServer 进程
|	if (startSystemServer)
    |	Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
	|	r.run();
	|	return;  // for SystemServer 进程 后直接回来,退出进程
//	默认状况,运行 runSelectLoop ,敞开 zygoteServer 循环,等候 AMS 创立进程的socket音讯
|	caller = zygoteServer.runSelectLoop(abiList);
|	if (caller != null)  // fork 完结的子进程,会从runSelectLoop无线循环中跳出,会进入到这儿
    /*
    假如是子进程的话,这儿回来的是 MethodAndArgsCaller,MethodAndArgsCaller 承继Runnable
    这儿不像曾经那样抛出反常整理栈帧,便是回退到 ZygoteInit.main,经过 MethodAndArgsCaller.run调用 android.app.ActivityThread.main
    */
    |	caller.run();
ZygoteServer.runSelectLoop
Runnable runSelectLoop(String abiList);
//	socketFDs[0] 为 ZygoteServer 的fd,之后的数据为 衔接客户端的 socket fd
|	ArrayList<FileDescriptor> socketFDs = new ArrayList<>();
|	ArrayList<ZygoteConnection> peers = new ArrayList<>();
|	socketFDs.add(mZygoteSocket.getFileDescriptor());// ZygoteServer 的fd
|	peers.add(null);// 先add了一个null,用于和 socketFDs 共用一个下标变量 pollIndex 
|	while (true) 
    |	StructPollfd[] pollFDs;
    //	循环开端先把 socketFDs 的fd参加到数组 pollFDs 
	//	之后再把 usapPool 的 fd 参加到 pollFDs
    //	usapPoolEventFDIndex 记载 usapPool 开端索引
    //	poll监听 socketFDs 中的文件描述符
    |	Os.poll(pollFDs, pollTimeoutMs);
	|	while (--pollIndex >= 0)
        |	if (pollIndex == 0)
            //	pollIndex == 0 表明 ZygoteServer socket 事情
            |	ZygoteConnection newPeer = acceptCommandPeer(abiList); // 拿到衔接客户端的socket
			|	peers.add(newPeer);
			//	把客户端的fd放到数组,下一次循环,一起参加到poll监听
			|	socketFDs.add(newPeer.getFileDescriptor());
		|	else if (pollIndex < usapPoolEventFDIndex) 
            //	AMS 创立进程的客户端 socket 事情
            |	ZygoteConnection connection = peers.get(pollIndex);
			//	读取socket衔接的数据,并处理
			|	final Runnable command = connection.processCommand(this, multipleForksOK);
			//	//默认值为false,在子进程时,会调用 setForkChild 设置为 true
			|	if (mIsForkChild)
                //	子进程回来的是 承继Runnable的 MethodAndArgsCaller 目标
                |	return command; // 子进程直接回来 command ,并结束 runSelectLoop 循环
ZygoteConnection.processCommand
Runnable processCommand(ZygoteServer zygoteServer, boolean multipleOK);
// 创立 native 层目标 NativeCommandBuffer,用于读socket数据 
|	ZygoteCommandBuffer argBuffer = new ZygoteCommandBuffer(mSocket);
// 把 ZygoteCommandBuffer 传入ZygoteArguments
// 并调用 ZygoteArguments.parseArgs(ZygoteCommandBuffer args, int argCount)
// parseArgs 读取socket,并解析数据
|	parsedArgs = ZygoteArguments.getInstance(argBuffer);
|	if (parsedArgs.mPreloadPackage != null)
    // 假如是 WebViewZygote,预加载 WebView 的库
    |	handlePreloadPackage(...);
|	if (canPreloadApp() && parsedArgs.mPreloadApp != null) 
    // 假如是AppZygoteServer,会预加载apk
    |	handlePreloadApp(...);
/*
mInvokeWith InvokeWith  DEBUG 运用, wrap.sh 脚本相关
mStartChildZygote 创立子zygote进程
multipleOK = true
非体系进程(systemserver、体系App),ATMS便是 SYSTEM_UID 
符合以上条件调用 Zygote.forkAndSpecialize,这个和曾经也不相同了
*/
|	if (parsedArgs.mInvokeWith != null || parsedArgs.mStartChildZygote || !multipleOK || peer.getUid() != Process.SYSTEM_UID)
	|	pid = Zygote.forkAndSpecialize(...); // 曾经用这个,现在不用了
    |else  // 通常状况是走 else 分支,调用 Zygote.forkSimpleApps
        Runnable result = Zygote.forkSimpleApps(...);
		|-->static @Nullable Runnable forkSimpleApps(...);
			|	boolean in_child = argBuffer.forkRepeatedly(...);
				|	return nativeForkRepeatedly(...);
					| com_android_internal_os_ZygoteCommandBuffer_nativeForkRepeatedly(...);
					  | NativeCommandBuffer.readAllLines;
					  | int pid = zygote::forkApp(...); // fd 的处理
						| 	zygote::ForkCommon(...);
							|	pid_t pid = fork(); // 真正fork进程的地方
							//处于子进程时,pid=0,处理分配内存的设置等等
							|	return pid;
					  |//假如pid为0,处于子进程,return true;
			|	if (in_child) // 假如是子进程,调用 childMain
                |	return childMain(argBuffer, /*usapPoolSocket=*/null, /*writePipe=*/null);
				|else// 假如是 Zygote 进程,return null;
        |// 子进程回来时,result不为null,return result;    
子进程调用 Zygote.childMain
// frameworks/base/core/java/com/android/internal/os/Zygote.java
Zygote.forkSimpleApps(...);
|	childMain(argBuffer, /*usapPoolSocket=*/null, /*writePipe=*/null);
|-->private static Runnable childMain(ZygoteCommandBuffer argBuffer,LocalServerSocket usapPoolSocket,FileDescriptor writePipe);
|	specializeAppProcess(...);
	| nativeSpecializeAppProcess(...);
	| com_android_internal_os_Zygote_nativeSpecializeAppProcess();
		//	设置命名空间的存储目录挂载
		//	设置调度战略,selinux,调试形式,SetGids,内存分配形式 等等
	    |	SpecializeCommon(...);
	| Thread.currentThread().setPriority(Thread.NORM_PRIORITY); //设置进程优先级
|	return ZygoteInit.zygoteInit(args.mTargetSdkVersion,args.mDisabledCompatChanges,args.mRemainingArgs,null);
			|	RuntimeInit.commonInit();
				//	设置反常处理
				|	RuntimeHooks.setUncaughtExceptionPreHandler(loggingHandler);
				|	Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));
			|	ZygoteInit.nativeZygoteInit(); //  敞开 binder 音讯监听
				|--> com_android_internal_os_ZygoteInit_nativeZygoteInit
                    |--> gCurRuntime->onZygoteInit();
						|--> frameworks/base/cmds/app_process/app_main.cpp
                        |--> onZygoteInit();
							|	sp<ProcessState> proc = ProcessState::self();
							|	proc->startThreadPool();
			|	return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv, classLoader);
				|	return findStaticMain(args.startClass, args.startArgs, classLoader);
					|	return new MethodAndArgsCaller(m, argv); // MethodAndArgsCaller 是个 Runnable, [见:附]
// 层层 return 回退到 ZygoteInit.main,经过 MethodAndArgsCaller.run 调用 android.app.ActivityThread.main 
// 附:MethodAndArgsCaller
static class MethodAndArgsCaller implements Runnable {
    //...
    public void run() {
        mMethod.invoke(null, new Object[] { mArgs })
    }
}

三、android.app.ActivityThread.main

1、ActivityThread.main 到 AMS 流程

ActivityThread.main
  // 1.创立主线程的 Looper 目标。 main函数终究调用 Looper.loop();发动无线循环。
  | Looper.prepareMainLooper();  
  // 2.创立 ActivityThread 目标
  | ActivityThread thread = new ActivityThread();  
		// 在类成员中直接创立 ApplicationThread,ApplicationThread 承继 IApplicationThread.Stub 
		// IApplicationThread 是 APP 同 AMS 交互的接口 
	|	final ApplicationThread mAppThread = new ApplicationThread();			
  // 3. 调用 ActivityThread .attach 办法
  | thread.attach(false, startSeq);   
    | final IActivityManager mgr = ActivityManager.getService();
	// mAppThread 是 ApplicationThread 	
	// 经过binder调用AMS的attachApplication接口将 ApplicationThread 注册到AMS中
    | mgr.attachApplication(mAppThread, startSeq);  
	  // 进入systemserver进程 的 AMS 
      | AMS.attachApplicationLocked //直接转到 attachApplicationLocked
        |  ProcessRecord app;  
        | 【1】thread.bindApplication(...); //binder跨进程 回调 ApplicationThread bindApplication
          // bindApplication流程:
          /*app进程 ApplicationThread .handleBindApplication
            Dex文件的加载和Resource资源的加载
            创立运用的LoadedApk目标、创立Application的Context
            加载运用APK的Dex文件到内存中,加载APK的Resource资源
            调用LoadedApk.makeApplication函数,创立运用的Application目标
            履行运用 Application.onCreate 生命周期函数*/
        // 设置 ProcessRecord.mThread = IApplicationThread(thread)
        // 设置 ProcessRecord.mWindowProcessController.mThread = IApplicationThread(thread)      
        | app.makeActive(thread, mProcessStats);  
        //发动运用 Activity的 流程      
        | 【2】mAtmInternal.attachApplication(app.getWindowProcessController()); 
          | mRootWindowContainer.attachApplication(wpc);
            | RootWindowContainer::startActivityForAttachedApplicationIfNeeded//这儿Android 13 版别有些改变
              | mStackSupervisor.realStartActivityLocked(ActivityRecord r,WindowProcessController proc,boolean andResume,...)
                |	r.startFreezingScreenLocked(proc, 0); // 冻住屏幕
				|	r.setProcess(proc);  // ActivityRecord 相关 WindowProcessController
				//	创立 ClientTransaction 
				//	ClientTransaction.mClient = WindowProcessController.getThread() 是 App 端的 ApplicationThread
				//	运用 ActivityRecord.token 赋值 ClientTransaction.mActivityToken
				//	ClientTransaction.mActivityToken 会传入 客户端app进程
				// 注:Android12 用的 ActivityRecord.appToken, Android 12 ActivityRecord.appToken=ActivityRecord.token
				|	final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.token); 
				//  增加 LaunchActivityItem 回调,App进程会履行其execute办法,内部履行 handleLaunchActivity
				|	clientTransaction.addCallback(LaunchActivityItem.obtain(...))
                |	lifecycleItem = ResumeActivityItem.obtain(isTransitionForward, r.shouldSendCompatFakeFocus()); 
				//	App进程会履行 ResumeActivityItem.execute办法 ,内部调用 handleResumeActivity
				|	clientTransaction.setLifecycleStateRequest(lifecycleItem);
                //	传递Launch和Resume生命周期业务
                | 	mService.getLifecycleManager().scheduleTransaction(clientTransaction);
  // 4. 发动loop无线循环
  |  Looper.loop();

2、scheduleTransaction 跨进程调用,把业务传递到 APP进程

ClientLifecycleManager.scheduleTransaction(ClientTransaction transaction);
|	transaction.schedule();
|-->ClientTransaction.schedule();
	// IApplicationThread mClient; 
	|	mClient.scheduleTransaction(this) //ApplicationThread 承继 IApplicationThread
	|-->ApplicationThread.scheduleTransaction(ClientTransaction transaction);
		|	ActivityThread.this.scheduleTransaction(transaction);
		//	ActivityThread.scheduleTransaction 承继 ClientTransactionHandler.scheduleTransaction
		|-->ClientTransactionHandler.scheduleTransaction(ClientTransaction transaction);
			//	调用 LaunchActivityItem.preExecute 预处理作业
			|	transaction.preExecute(this); 
			|	sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); //post到主线程去处理
				|-->ActivityThread.H.handleMessage(Message msg);
					|	mTransactionExecutor.execute(transaction);	
						|	executeCallbacks(transaction);
							//	取出	ClientTransaction.mActivityToken 作为参数传入 LaunchActivityItem.execute
							|	final IBinder token = transaction.getActivityToken();
							//	这个 token = ActivityRecord.appToken
							|	LaunchActivityItem.execute(ClientTransactionHandler client, IBinder token,...);
								//	创立 ActivityClientRecord  ActivityClientRecord.token = token;
								//	Android 12 是在 preExecute 中创立,Android 13 改变到了execute 中
								|	ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,...);
								// 履行 ActivityThread.handleLaunchActivity
								|	client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
						|	executeLifecycleState(transaction);
							|	ResumeActivityItem.execute(ClientTransactionHandler client, ActivityClientRecord r,...);
								//	履行 ActivityThread.handleResumeActivity
                                |	client.handleResumeActivity(r, true /* finalStateRequest */, mIsForward,...);

ActivityClientRecord.token = ClientTransaction.mActivityToken = ActivityRecord.token

经过一系列的 业务,生命周期管理相关的代码后 调用 handleLaunchActivity 和 handleResumeActivity

3、handleLaunchActivity

  • 履行 Launch 生命周期
//	frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
//	frameworks/base/core/java/android/app/ActivityThread.java
ActivityThread.handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent);
|	performLaunchActivity(ActivityClientRecord r, Intent customIntent)
    //	1.创立Activity的Context,Activity虽然也是Context,可是其真正的Context是Activity.mBase 成员    
    |	ContextImpl appContext = createBaseContextForActivity(r);
    //	2.调用 mInstrumentation.newActivity,经过反射创立Activity
    |	java.lang.ClassLoader cl = appContext.getClassLoader();
	|	activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent);
	//  把 ActivityClientRecord 存入 mActivities
	//	ActivityClientRecord.activity 存储 Activity 目标
	|	mActivities.put(r.token, r);
    //  3.调用 activity.attach 办法
	|	activity.attach(appContext, this, getInstrumentation(), r.token, r.ident, app, r.intent, r.activityInfo,...);
		//	把 performLaunchActivity 创立的 context 设置到 Activity.mBase
		|	attachBaseContext(context);
		//  创立 PhoneWindow 目标
		|	mWindow = new PhoneWindow(this, window, activityConfigCallback);
			|	mWindowAttributes = new WindowManager.LayoutParams();
				// 这个 type 在后边 Window.adjustLayoutParamsForSubWindow 会用到
				|	type = TYPE_APPLICATION;	
		//	设置Activity key dispatching, panels and menus 等回调。用于拦截点击接触事情等等
		|	mWindow.setCallback(this);
//至此:
//	activity.mToken = ActivityClientRecord.token = ClientTransaction.mActivityToken = ActivityRecord.token
		|	mToken = token;
		|	mApplication = application;
		//	给 PhoneWindow 目标,设置 WindowManager 目标
        |	mWindow.setWindowManager((WindowManager)context.getSystemService(Context.WINDOW_SERVICE), mToken, ...);
		//	SystemServiceRegistry 静态代码中创立 getSystemService 接口的 WindowManager 实例:
			|	new WindowManagerImpl(ctx);
				// SystemServiceRegistry 创立的WindowManagerImpl的成员 mParentWindow=null; mWindowContextToken=null;
				|	this(context, null /* parentWindow */, null /* clientToken */);
		|-->Window.setWindowManager(WindowManager wm, IBinder appToken, String appName,boolean hardwareAccelerated);
//至此:
//PhoneWindow.mAppToken=activity.mToken = ActivityClientRecord.token = ClientTransaction.mActivityToken = ActivityRecord.token
			|	mAppToken = appToken;
			|	mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);// 参数传入 PhoneWindow
			|-->WindowManagerImpl createLocalWindowManager(Window parentWindow) 
				|	return new WindowManagerImpl(mContext, parentWindow, mWindowContextToken);
					|	mContext = context;
					|	mParentWindow = parentWindow; // 这个传入的是 PhoneWindow
					|	mWindowContextToken = windowContextToken; // 这个是 null
            | 	这个 mWindowManager 目标时new的 WindowManagerImpl
            // 	也便是说Activity中的 mWindowManager 目标,获取的window管理器是 WindowManagerImpl
        |	mWindowManager = mWindow.getWindowManager(); 
	|	r.activity = activity;	//	ActivityClientRecord 相关 activity
	//	4.Instrumentation.callActivityOnCreate--->Activity.onCreate	
    |	mInstrumentation.callActivityOnCreate
          // 履行Activity的onCreate生命周期函数
          // 在 setContentView 调用installDecor创立 DecorView 目标
          // 并设置 DecorView 的window目标为 PhoneWindow 
		|	Activity.performCreate
      		|	Activity.onCreate
        		|	Activity.setContentView(R.layout.activity_main);
          			|	getWindow().setContentView
            			|	PhoneWindow.installDecor()
                    		|	mDecor = generateDecor(-1);
								|	return new DecorView(context, featureId, this, getAttributes());
								|-->DecorView(Context context,..., PhoneWindow window,WindowManager.LayoutParams params)
									|	setWindow(window);
										|	mWindow = window; //PhoneWindow;		

4、handleResumeActivity

  • 履行Resume生命周期
//	frameworks/base/core/java/android/app/servertransaction/ResumeActivityItem.java
client.handleResumeActivity(r, true /* finalStateRequest */, mIsForward, mShouldSendCompatFakeFocus, "RESUME_ACTIVITY");
//	frameworks/base/core/java/android/app/ActivityThread.java
// 履行运用Activity的onResume生命周期函数
ActivityThread.handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest,boolean isForward, ...) 
  |	  performResumeActivity(r, finalStateRequest, reason);
	  | 履行运用Activity的onResume生命周期函数
      | r.activity.performResume(r.startsNotResumed, reason); 
			|	mInstrumentation.callActivityOnResume(this);
	  			|	activity.onResume();	
  //  handleResumeActivity中履行结束performResumeActivity后,继续履行以下代码:
  |   final Activity a = r.activity;
  |	  r.window = r.activity.getWindow(); // 赋值 ActivityClientRecord.window
  |	  View decor = r.window.getDecorView();
  |	  decor.setVisibility(View.INVISIBLE);
  |   ViewManager wm = a.getWindowManager(); //activity.attach 中创立的 WindowManagerImpl 目标  
  //  回来的是  Window.mWindowAttributes,即 l = 	PhoneWindow.mWindowAttributes
  |   WindowManager.LayoutParams l = r.window.getAttributes();
  |	  wm.addView(decor, l);
  |-->WindowManagerImpl.addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params)
      |	  applyTokens(params); // 这儿虽然看上去是设置 WindowManager.LayoutParams.token 但剖析下来不是,还要在后边
		  |	  final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
		  |	  if(mDefaultToken != null )	wparams.token = mDefaultToken; // 不进这个流程
		  |   wparams.mWindowContextToken = mWindowContextToken;  // 现在为止仍是 null
	  |   mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow, mContext.getUserId());
	  |-->WindowManagerGlobal.addView(View view, ViewGroup.LayoutParams params, Window parentWindow, ...)
          |   final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;	
		  //  设置 WindowManager.LayoutParams 的 token、title、packageName、flags 特点	
          |	  parentWindow.adjustLayoutParamsForSubWindow(wparams);
		  |-->Window.adjustLayoutParamsForSubWindow(WindowManager.LayoutParams wp)
              	//  wp.type = TYPE_APPLICATION =2; 假如是startingwindow,这儿 wp.type = 3 (startingwindow的flag)
				|	wp.token = mContainer == null ? mAppToken : mContainer.mAppToken;
				//	由于 mContainer 是 null, 所以 wp.token = mAppToken 	
/*至此:
PhoneWindow.mAppToken = activity.mToken = ActivityClientRecord.token = ClientTransaction.mActivityToken = ActivityRecord.token
PhoneWindow.mWindowAttributes.token = PhoneWindow.mAppToken */
  		  |	  ViewRootImpl root = new ViewRootImpl(view.getContext(), display); //创立ViewRootImpl目标
		  //  ViewRootImpl结构函数	
		  |-->ViewRootImpl(Context context, Display display);
				|	结构函数中创立IWindowSession  目标,用于同 wms 通讯
                |	this(context, display, WindowManagerGlobal.getWindowSession(), false /* useSfChoreographer */); 
					|	private static IWindowSession sWindowSession = windowManager.openSession(...)
                    |	mWindowSession = sWindowSession	
                    //  W extends IWindow.Stub ,作为参数传递给WMS,用于同 WMS 通讯    
                    |	mWindow = new W(this);    
                    |	创立 Choreographer 目标	
                    |	mChoreographer = useSfChoreographer ? Choreographer.getSfInstance() : Choreographer.getInstance();
						|	mChoreographer = Choreographer.getInstance();//以上代码简写
		  |	  
		  |	  view.setLayoutParams(wparams);
      	  |	  mViews.add(view);
		  |	  mRoots.add(root);
  		  |	  mParams.add(wparams);
 		  //  来到要害点  ViewRootImpl.setview
		  |	  root.setView(view, wparams, panelParentView, userId);

setview之后看surface创立流程

四、ViewRootImpl 注册vsync回调

注册vsync回调流程:Choreographer

WindowManagerGlobal:: mGlobal.addView
    |	ViewRootImpl root = new ViewRootImpl(view.getContext(), display); //创立ViewRootImpl目标
		|	结构函数中创立 IWindowSession  目标,用于同 wms 通讯
        |	 this(context, display, WindowManagerGlobal.getWindowSession(), false /* useSfChoreographer */);
			|	private static IWindowSession sWindowSession = windowManager.openSession(...)
            |	mWindowSession = sWindowSession;
			|	创立 Choreographer 目标
            |	mChoreographer = useSfChoreographer ? Choreographer.getSfInstance() : Choreographer.getInstance();
				//  以上代码简写:
				|	mChoreographer = Choreographer.getInstance(); 
				|-->Choreographer::Choreographer getInstance();
					//  获取当时线程的 Choreographer,假如当时线程没有,就调用ThreadLocal.initialValue()创立一个新的 Choreographer
					|	return sThreadInstance.get();
						|	ThreadLocal.initialValue();
							|	Looper looper = Looper.myLooper(); 
							|	return new Choreographer(looper, VSYNC_SOURCE_APP); // VSYNC_SOURCE_APP = 0;
								//	Choreographer 结构函数:
								|	Choreographer(Looper looper, int vsyncSource)
                                    |	mLooper = looper;
									|	mHandler = new FrameHandler(looper);
									//  创立 FrameDisplayEventReceiver,内部创立 IDisplayEventConnection,并创立vsync的通讯socket
									|	mDisplayEventReceiver = new FrameDisplayEventReceiver(looper, vsyncSource);
									|	mFrameIntervalNanos = (long)(1000000000 / getRefreshRate());
									//	CALLBACK_LAST = 4
									|	mCallbackQueues = new CallbackQueue[CALLBACK_LAST + 1];	
									//	创立 5 个CallbackQueue	
									|	for (int i = 0; i <= CALLBACK_LAST; i++)
                                        |	mCallbackQueues[i] = new CallbackQueue();

注册vsync回调流程:EventThread

Choreographer 结构函数创立 FrameDisplayEventReceiver 时,会创立同SurfaceFlinger的EventThread线程通讯的 IDisplayEventConnection

IDisplayEventConnection界说了以下接口:

  • void stealReceiveChannel(out BitTube outChannel);获取socket通讯管道
  • void setVsyncRate(in int count); 设置vsync分发速率。0,不调用requestNextVsync不分发;1,每次vsync事情都分发;其他,每N个vsync事情分发一次
    • 体系默以为 0 ,不调用requestNextVsync不分发
  • oneway void requestNextVsync(); 恳求vsync
  • ParcelableVsyncEventData getLatestVsyncEventData(); 获取最新的

获取到 IDisplayEventConnection 后,会马上调用 stealReceiveChannel 获取socket通讯管道

从 FrameDisplayEventReceiver 结构函数开端:

注册vsync回调流程:APP进程端
Choreographer choreographer = new Choreographer(Looper.myLooper(), VSYNC_SOURCE_APP);
	|	//	Choreographer 结构函数中 new FrameDisplayEventReceiver
	|	mDisplayEventReceiver = new FrameDisplayEventReceiver(looper, vsyncSource);
// FrameDisplayEventReceiver 结构函数:
//参数 looper:当时线程的looper;	vsyncSource = VSYNC_SOURCE_APP =0;
FrameDisplayEventReceiver(Looper looper, int vsyncSource);
|	super(looper, vsyncSource, 0);
	//	FrameDisplayEventReceiver 承继 DisplayEventReceiver
    |	DisplayEventReceiver(Looper looper, int vsyncSource, int eventRegistration);
     	|	mMessageQueue = looper.getQueue();
		//	创立 NativeDisplayEventReceiver,把目标地址存储到java层的 DisplayEventReceiver.mReceiverPtr 中
		|	mReceiverPtr = nativeInit(this, mMessageQueue,vsyncSource, eventRegistration);
			//	frameworks/base/core/jni/android_view_DisplayEventReceiver.cpp
			|	nativeInit(..., jobject receiverWeak, jobject messageQueueObj,jint vsyncSource, jint eventRegistration)
                |	sp<NativeDisplayEventReceiver> receiver = 
                |			new NativeDisplayEventReceiver(env, receiverWeak, messageQueue, vsyncSource, eventRegistration);
					//	NativeDisplayEventReceiver 结构函数继续调用父类 DisplayEventDispatcher 的结构函数
					//	DisplayEventDispatcher 结构函数中创立成员变量 DisplayEventReceiver mReceiver(vsyncSource, eventRegistration)
					//	DisplayEventReceiver 结构函数:
					//	frameworks/native/libs/gui/DisplayEventReceiver.cpp
					|	DisplayEventReceiver(ISurfaceComposer::VsyncSource vsyncSource,EventRegistrationFlags eventRegistration)
                        //	获取 SurfaceFlinger 服务
                        |	sp<ISurfaceComposer> sf(ComposerService::getComposerService());
						//	获取 IDisplayEventConnection 存储到成员变量 mEventConnection
						|	mEventConnection = sf->createDisplayEventConnection(vsyncSource, eventRegistration);
							//进入 BpSurfaceComposer.createDisplayEventConnection 开端binder通讯
						|-->createDisplayEventConnection(VsyncSource vsyncSource, EventRegistrationFlags eventRegistration)
                            //  【见 “SurfaceFlinger进程端注册vsync流程” 章节】    
                            |	remote()->transact(BnSurfaceComposer::CREATE_DISPLAY_EVENT_CONNECTION,data, &reply);
							|	result = interface_cast<IDisplayEventConnection>(reply.readStrongBinder());
							|	return result;
						|	mDataChannel = std::make_unique<gui::BitTube>();
						//	获取进程间通讯 socket 管道,封装到 BitTube 中,存储到成员变量 mDataChannel
						//	【详情,见 “SurfaceFlinger进程端注册vsync流程” 章节】 
						|	mEventConnection->stealReceiveChannel(mDataChannel.get());
				|	receiver->initialize();
					|	DisplayEventDispatcher.initialize()
                    //	把 socket 参加    
                    |	mLooper->addFd(mReceiver.getFd(), 0, Looper::EVENT_INPUT, this, NULL);    
				|	receiver->incStrong(gDisplayEventReceiverClassInfo.clazz);
				|	return reinterpret_cast<jlong>(receiver.get());
注册vsync回调流程:SurfaceFlinger 进程端

BpSurfaceComposer.createDisplayEventConnection 跨进程进入 SurfaceFlinger 端

//	frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
//	参数vsyncSource = VSYNC_SOURCE_APP = 0; eventRegistration = 0
SurfaceFlinger.createDisplayEventConnection(ISurfaceComposer::VsyncSource vsyncSource,EventRegistrationFlags eventRegistration);
|	//	eVsyncSourceSurfaceFlinger = 1
|   //	handle = mAppConnectionHandle    
|	const auto& handle = vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
|	return mScheduler->createDisplayEventConnection(handle, eventRegistration);
|-->Scheduler.createDisplayEventConnection(ConnectionHandle handle, ISurfaceComposer::EventRegistrationFlags eventRegistration)	
    //	std::unordered_map<ConnectionHandle, Connection> mConnections;
    //	mConnections 存储的 Connection 是个结构体。仅含有两个成员变量 EventThreadConnection 和 EventThread  [拜见:附]
    //	mConnections[handle].thread.get() 获取 SurfaceFlinger.mAppConnectionHandle 对应的 EventThread, App的EventThread线程
	|	return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration);
	|-->Scheduler.createConnectionInternal( EventThread* eventThread, EventRegistrationFlags eventRegistration)
		|	return eventThread->createEventConnection([&] { resync(); }, eventRegistration);
		|-->EventThread.createEventConnection(ResyncCallback resyncCallback, EventRegistrationFlags eventRegistration)
            //	EventThreadConnection 承继 IDisplayEventConnection ,回来APP的IDisplayEventConnection 便是 EventThreadConnection
            |	return new EventThreadConnection(this,IPCThreadState::self()->getCallingUid(),resyncCallback,eventRegistration)
            //	EventThreadConnection 结构函数:                                     
            |-->EventThreadConnection(EventThread* eventThread, uid_t callingUid, ResyncCallback resyncCallback,...)
            	|	: resyncCallback(std::move(resyncCallback)),
                |	mOwnerUid(callingUid),
                |   mEventRegistration(eventRegistration),                             
                |   mEventThread(eventThread),   
                //	创立 BitTube,BitTube 结构函数中创立 socketpair                                 
                |   mChannel(gui::BitTube::DefaultSize){} 
                    //	BitTube 结构函数                             
					|	BitTube::BitTube(size_t bufsize)
                        |	init(bufsize, bufsize);
                         	|	int sockets[2];
                            |	socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets);	// 创立 socketpair
                            |	mReceiveFd.reset(sockets[0]); // sockets[0] 赋值给 mReceiveFd ,未来会发送到 APP 进程端  
                            |	mSendFd.reset(sockets[1]); 
            //	EventThreadConnection 创立完结后,初次 sp 指针引证时调用 onFirstRef()
            |	EventThreadConnection.onFirstRef();
                //	注册 vsync 回调                                 
                |	mEventThread->registerDisplayEventConnection(this);                                 	
                |-->EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection);
                    |	// 参加vector调集 mDisplayEventConnections
                    | 	// 这个调集 mDisplayEventConnection 会在 EventThread::threadMain 循环遍历                           
                    |	mDisplayEventConnections.push_back(connection);
                    |	mCondition.notify_all();  
// App进程端获取到 IDisplayEventConnection 后,立即就调用了stealReceiveChannel 接口获取 socket fd:                                                  
|-->EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel)
    //	把结构EventThreadConnection时,创立的 socketpair的fd 写到APP进程的 BitTube 中
    |	outChannel->setReceiveFd(mChannel.moveReceiveFd());
	|	outChannel->setSendFd(base::unique_fd(dup(mChannel.getSendFd())));                                                
// 附: Scheduler.Connection 结构体
    struct Connection {
        sp<EventThreadConnection> connection;
        std::unique_ptr<EventThread> thread;
    };

五、ViewRootImpl.setView

  1. 注册 vsync 回调 IDisplayEventConnection
  2. ViewRootImpl.setView 函数中调用 requestLayout 恳求vsync流程
  3. ViewRootImpl.setView 函数中调用 WindowSession.addToDisplayAsUser **创立 ISurfaceComposerClient **
    • addToDisplayAsUser 还有个功用是 创立 InputChannel

​ 传入一个null的 inputChannel 目标到 addToDisplayAsUser,这个 inputChannel ,在wms端创立,并赋值到inputChannel ,实际便是 socketpair

  1. vsync回调回来后 调用ViewRootImpl.**relayoutWindow 创立 Surface **

ViewRootImpl.requestLayout 恳求vsync流程

衔接第三章的 setView

//	frameworks/base/core/java/android/view/WindowManagerGlobal.java
root.setView(view, wparams, panelParentView, userId); // 调用ViewRootImpl 的setview办法 要害办法
//	frameworks/base/core/java/android/view/ViewRootImpl.java
ViewRootImpl.setView(View view, WindowManager.LayoutParams attrs, View panelParentView)
//【一】、恳求vsync:
| requestLayout();  //恳求vsync ,vsync回调后,敞开界面绘制流程======!!!!!!!!!!!!!**
  | scheduleTraversals();
    |	mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
    |-->Choreographer.postCallback(int callbackType, Runnable action, Object token)
      	| postCallbackDelayed(callbackType, action, token, 0);
      	| postCallbackDelayedInternal(callbackType, action, token, delayMillis);
            // 这儿把 mTraversalRunnable 参加到 mCallbackQueues 数组
            | mCallbackQueues[callbackType].**addCallbackLocked**(dueTime, action, token);
      		| scheduleFrameLocked
                | scheduleVsyncLocked();
     		       |   mDisplayEventReceiver.scheduleVsync();
      			   |-->DisplayEventReceiver.scheduleVsync();
      					| nativeScheduleVsync(mReceiverPtr);
        					// android_view_DisplayEventReceiver.cpp 
                            | nativeScheduleVsync()
          						// DisplayEventDispatcher.cpp
                                | scheduleVsync()
									//IDisplayEventConnection mEventConnection=sf->createDisplayEventConnection
          							| mReceiver.requestNextVsync();
									// 之后跨进程调用到 SurfaceFlinger 的 requestNextVsync 办法
            						| DisplayEventReceiver.cpp--requestNextVsync(); 
              							| mEventConnection->requestNextVsync();
              							| EventThreadConnection::requestNextVsync()
              							| EventThread::requestNextVsync(const sp<EventThreadConnection>& connection)
                							| mCondition.notify_all();//唤醒 app EventThread 线程
											//sf 发动后 EventThread 线程会在 threadMain 循环
                							| EventThread::threadMain(std::unique_lock<std::mutex>& lock)
                  								| mCondition.wait(lock);// 从阻塞中唤醒
                  								| mVSyncSource->setVSyncEnabled(true);
                    								| DispSyncSource::setVSyncEnabled(bool enable)
                    								| 又经过许多代码,终究:
                    								| VSyncDispatchTimerQueue::setTimer(nsecs_t targetTime, nsecs_t /*now*/)
                    								| Timer::alarmAt(std::function<void()> const& cb, nsecs_t time)
                    								| 终究的终究调用“体系调用”,timerfd_settime 设置守时发送vsync
                    								| timerfd_settime(mTimerFd, TFD_TIMER_ABSTIME, &new_timer, &old_timer)
            | 之后便是异步代码了,之后很快就发动了vsync,之后vsync事情回调app进程的doFrame办法

IWindowSession.addToDisplayAsUser–>WMS.addWindow

  • 1、创立 WindowState
  • 2、创立 InputChannel
  • 3、创立同 SurfaceFlinger 的衔接 ISurfaceComposerClient
  • 4、更新焦点
root.setView(view, wparams, panelParentView, userId);
//	frameworks/base/core/java/android/view/ViewRootImpl.java
ViewRootImpl.setView(View view, WindowManager.LayoutParams attrs, View panelParentView);
|	mView = view; // 把 DecorView 存储到 mView 
//	把 WindowManagerGlobal.addView 设置过 token 的wparams数据仿制到 mWindowAttributes
|	mWindowAttributes.copyFrom(attrs);
/*至此:
WindowToken.token 是 IBinder 类
ActivityRecord 承继 WindowToken
ActivityRecord 有个内部类 ActivityRecord.Token 承继 Binder
ActivityRecord.token 这个成员承继自 WindowToken,是内部类 ActivityRecord.Token 的实例
PhoneWindow.mAppToken = activity.mToken = ActivityClientRecord.token = ClientTransaction.mActivityToken = ActivityRecord.token
ViewRootImpl.mWindowAttributes.mToken = PhoneWindow.mWindowAttributes.token = PhoneWindow.mAppToken 
*/
//	参加 PRIVATE_FLAG_USE_BLAST flag,这个flag在创立  SurfaceControl 时会用到 
|	mWindowAttributes.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_USE_BLAST;
//	【一】、恳求vsync
|	requestLayout();
|	InputChannel inputChannel = null; // 一个null的inputChannel,传递到WMS端赋值
//	【二】、创立 ISurfaceComposerClient
//  mWindow 参数为 [W extends IWindow.Stub],作为参数传递给WMS,用于同 WMS 通讯
|	mWindowSession.addToDisplayAsUser(mWindow, mWindowAttributes..., userId,..., inputChannel, mTempInsets,...)
    //	参数 attrs.token = ActivityRecord.token
	|-->WindowManagerService.mService.addWindow(this, window, attrs, viewVisibility, displayId, userId, equestedVisibility, outInputChannel, outInsetsState, outActiveControls);
		// 【1】、从 DisplayContent.mTokenMap 中检索token
		//  在 setNewTask 时,以ActivityRecord.token为键,已经把ActivityRecord参加了DisplayContent.mTokenMap
		//	所以能取到 token, 这个token不为 null
		|   WindowToken token = displayContent.getWindowToken(hasParent ? parentWindow.mAttrs.token : attrs.token);
		//	假如 token为null,这儿会走创立token流程:
		//	binder 为 ViewRootImpl.mWindowAttributes.mToken = ActivityRecord.token
		|   final IBinder binder = attrs.token != null ? attrs.token : client.asBinder();	
		//	WindowToken 结构函数中,传入的 DisplayContent 参数不为null时,参加 DisplayContent.mTokenMap
		|   token = new WindowToken.Builder(this, binder, type).setDisplayContent(displayContent)....build();
		|		// WindowToken 结构函数:
    	|		WindowToken(WindowManagerService service, IBinder _token, int type...DisplayContent dc,...)
        		|	token = _token;
				|	if (dc != null) dc.addWindowToken(token, this); // 参加 DisplayContent.mTokenMap
		// 【2】、创立 WindowState 
  		|   WindowState win = new WindowState(this, session, client, token, parentWindow, appOp[0], attrs, viewVisibility, session.mUid, userId, session.mCanAddInternalSystemWindow);
		//  WindowState结构函数
		|-->WindowState(WindowManagerService service, Session s, IWindow c, WindowToken token,WindowState parentWindow...)
        	|	mSession = s;
			|	mClient = c;
			|	mToken = token;
/*至此:
PhoneWindow.mAppToken = activity.mToken = ActivityClientRecord.token = ClientTransaction.mActivityToken = ActivityRecord.token
参数attrs.token = ViewRootImpl.mWindowAttributes.mToken = PhoneWindow.mWindowAttributes.token = PhoneWindow.mAppToken 
WindowState.mToken = ActivityRecord */
			|	mActivityRecord = mToken.asActivityRecord(); // 把token转为 ActivityRecord
			|	InputApplicationHandle tempIAHandle = mActivityRecord.getInputApplicationHandle(false);
            |-->ActivityRecord.getInputApplicationHandle(boolean update);
            |	|	mInputApplicationHandle = new InputApplicationHandle(token, toString(),mInputDispatchingTimeoutMillis);
			|		//	InputApplicationHandle 结构函数:
			|		|-->InputApplicationHandle(@NonNull IBinder token, @NonNull String name,long dispatchingTimeoutMillis);
			|			|	this.token = token;
			|	|	return mInputApplicationHandle;
			|	//创立 InputWindowHandleWrapper,包装为InputWindowHandle,用于输入输出,焦点更新等等,是wms,SurfaceFlinger,input 传递数据的目标
			|	mInputWindowHandle = new InputWindowHandleWrapper(new InputWindowHandle(tempIAHandle, getDisplayId()))
            |	//	InputWindowHandle  结构函数: 
            |	|-->InputWindowHandle(InputApplicationHandle inputApplicationHandle, int displayId);
            |    	|	this.inputApplicationHandle = inputApplicationHandle;	
            |	//  InputWindowHandleWrapper 结构函数:  
            |	|-->InputWindowHandleWrapper(@NonNull InputWindowHandle handle);
			|		// WindowState.mInputWindowHandle.mHandle 为InputWindowHandle目标,这个目标会传到 SurfaceFlinger
			|		// WindowState.mInputWindowHandle.mHandle.inputApplicationHandle.token = ActivityRecord.token
            |    	|	mHandle = handle;
			|	mWinAnimator = new WindowStateAnimator(this);// 创立 WindowStateAnimator
		// 【3】、InputChannel 创立流程:
		|   win.openInputChannel(outInputChannel);
		|-->WindowState.openInputChannel(InputChannel outInputChannel);
			|	mInputChannel = mWmService.mInputManager.createInputChannel(name);
				|-->InputManagerService.createInputChannel(String name);
                    |-->NativeInputManagerService.createInputChannel(String name);
                    	|-->nativeCreateInputChannel(JNIEnv* env, jobject nativeImplObj, jstring nameObj);
                    		|-->NativeInputManager.createInputChannel(const std::string& name);
                    			|-->InputDispatcher::createInputChannel(const std::string& name);
									|	std::unique_ptr<InputChannel> serverChannel;
									|	std::unique_ptr<InputChannel> clientChannel;
									//	1、创立 socketpair	
									|	InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
									|-->InputChannel::openInputChannelPair(...InputChannel outServerChannel,outClientChannel)
										|	int sockets[2];
										|	socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets);// 创立 socketpair	
                                        |	sp<IBinder> token = new BBinder(); //  创立token
										|	std::string serverChannelName = name + " (server)";
										|	outServerChannel = InputChannel::create(serverChannelName, sockets[0], token);
										|	std::string clientChannelName = name + " (client)";
										|	outClientChannel = InputChannel::create(clientChannelName, sockets[1], token);
									//  获取InputChannel.mToken, 这个 token = new BBinder();
                                    |	const sp<IBinder>& token = serverChannel->getConnectionToken();
									//	2、运用 serverChannel 创立 connection
									|	sp<Connection> connection = new Connection(std::move(serverChannel), false , ...);
									//	以token为键,把 connection 参加 mConnectionsByToken
									//	serverChannel 和 clientChannel 共用一个token,用来寻觅互相
									//	服务端参加mConnectionsByToken,一个回来到WMS,WMS再回来给App
									|	mConnectionsByToken.emplace(token, connection);
									//	3、服务端的 socket fd 参加 epoll 监听
									|	int fd = serverChannel->getFd();
									|	mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
									|	mLooper->wake();
									|	return clientChannel; // 回来客户端的 InputChannel 
			|	mInputChannelToken = mInputChannel.getToken(); // 获取 native 创立的 token
			//	mInputWindowHandle.
			|	mInputWindowHandle.setToken(mInputChannelToken);
				// WindowState.InputWindowHandleWrapper.InputWindowHandle.token = native层创立的 token
				//	InputWindowHandle.token 这个token 很重要,是 SurfaceFlinger,input 沟通用的令牌,比方焦点更新
				//	InputWindowHandle.InputApplicationHandle.token = ActivityRecord.token
				//	wms会透过 SurfaceTransition 把InputWindowHandle传递给 SurfaceFlinger 的 Layer.mDrawingState.inputInfo
				//	到这儿 Inputms,wms,ams, SurfaceFlinger 就这么衔接起来了。
				|	mHandle.token = token;
			//	以 mInputChannelToken 为键,把 WindowState 存入WMS的 HashMap
			|	mWmService.mInputToWindowMap.put(mInputChannelToken, this);
			//	把 native 层创立的客户端InputChannel回来给 APP 
			|	mInputChannel.copyTo(outInputChannel);
		|	res = ADD_OKAY;
		|	// mUseBLAST = (settings get global  use_blast_adapter_vr == 1)
        |   // global settings 中没有设置这个 use_blast_adapter_vr 值的话,默认值为 true
		|	if (mUseBLAST)	res |= WindowManagerGlobal.ADD_FLAG_USE_BLAST;
		// 【4】、 创立 SurfaceSession---> 创立SurfaceFlinger的客户端 ISurfaceComposerClient
  		|   win.attach();
    		|	mSession.windowAddedLocked();
				//WindowState.mSession.mSurfaceSession.mNativeClient.mClient保存了用于SurfaceFlinger通讯的 ISurfaceComposerClient
      			|	Session.mSurfaceSession = new SurfaceSession();
        			//	SurfaceSession  内容很少,大概60行的代码。便是个 Native 的Java包装类
					//	SurfaceSession.mNativeClient 是个 SurfaceComposerClient 类
					//	SurfaceComposerClient.mClient 成员是个 ISurfaceComposerClient, 用于SurfaceFlinger通讯
        			|	SurfaceSession.mNativeClient = nativeCreate();
          				//	android_view_SurfaceSession.cpp 
          				|	android_view_SurfaceSession.nativeCreate
            				|	SurfaceComposerClient* client = new SurfaceComposerClient();
							//  sp指针引证会调用 SurfaceComposerClient::onFirstRef() 
            				|	client->incStrong((void*)nativeCreate);
              					|	SurfaceComposerClient::onFirstRef()
                                    |	sp<ISurfaceComposer> sf(ComposerService::getComposerService());
									//	SurfaceComposerClient.mClient 是 ISurfaceComposerClient
                					|	mClient = sf->createConnection();
            				|	return client;
		//	以 IWindow 为键,把 WindowState 参加到 mWindowMap
		| 	mWindowMap.put(client.asBinder(), win);
		//	把 WindowState 参加到  ActivityRecord.token ,成为其子节点
		//  ActivityRecord.mSurfaceControl  和  WindowState.mSurfaceControl 应该都会创立。
		//  这个流程会创立 WindowState.mSurfaceControl,承继的父类 WindowToken.mSurfaceControl
		//	TODO: 这儿的代码应该没这么简略,详细流程待研讨。创立SurfaceControl,意味着创立Layer。这儿应该是创立 ContainerLayer 和 EffectLayer 相关
		| 	win.mToken.addWindow(win);
		|-->WindowToken.addWindow(final WindowState win)
            |	if (mSurfaceControl == null)
                |	createSurfaceControl(true /* force */);
		//	更新焦点
		| 	updateFocusedWindowLocked(UPDATE_FOCUS_WILL_ASSIGN_LAYERS,false /*updateInputWindows*/);		

六、vsync 回调

1、SurfaceFlinger进程端: vsync 事情分发

这儿简略写写吧

EventThread::onVSyncEvent(nsecs_t timestamp, VSyncSource::VSyncData vsyncData)
|	mPendingEvents.push_back(makeVSync(mVSyncState->displayId, timestamp, ++mVSyncState->count,...);
|	mCondition.notify_all(); // 唤醒 EventThread::threadMain 处wait代码
EventThread::threadMain(std::unique_lock<std::mutex>& lock)
|	std::vector<sp<EventThreadConnection>> consumers;
|	while (mState != State::Quit) 
    |	std::optional<DisplayEventReceiver::Event> event;
	|	//...
	|	if (mState == State::Idle) {//	界面不动,进这儿wait
    	|	mCondition.wait(lock);
    |	//...    
	|	if (!mPendingEvents.empty()) // 被唤醒后开端处理 mPendingEvents
        |	event = mPendingEvents.front();
		|	mPendingEvents.pop_front();
	|	//...
    |	auto it = mDisplayEventConnections.begin();
    |	// mDisplayEventConnections是存储所有 EventThreadConnection 的 vector
	|	while (it != mDisplayEventConnections.end())
        |	//  EventThreadConnection 为虚引证,这儿 promote 提升为强引证
        |	if (const auto connection = it->promote())
            |	if (event && shouldConsumeEvent(*event, connection))
                |	// 关于需求消费这个事情的EventThreadConnection存入入 vector 中
            	|	consumers.push_back(connection);
			|	 ++it;
		|	else
            |	it = mDisplayEventConnections.erase(it);// 假如虚引证的目标毁掉了,则从调集删去
    |	if (!consumers.empty()) {//调集不为空,开端分发事情
        |	dispatchEvent(*event, consumers);
        |-->EventThread::dispatchEvent(const DisplayEventReceiver::Event& event, const DisplayEventConsumers& consumers)
            |	for (const auto& consumer : consumers)
                |	DisplayEventReceiver::Event copy = event;
                |	generateFrameTimeline(copy.vsync.vsyncData,...);
        		|	consumer->postEvent(copy)
                |-->EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event)
                    |	DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
        				|	gui::BitTube::sendObjects(dataChannel, events, count);
        					|	ssize_t size = tube->write(vaddr, count * objSize);
        					|-->BitTube::write(void const* vaddr, size_t size)
                                |	// mSendFd 是 socketpair 的fd
                                |	len = ::send(mSendFd, vaddr, size, MSG_DONTWAIT | MSG_NOSIGNAL);

2、APP进程端:接纳vsync回调

epoll回调
| DisplayEventDispatcher::handleEvent
  	| processPendingEvents 运用 socketpair 的BitTube 在d中取出 VSync 事情
    	| DisplayEventReceiver::getEvents() 
    	| BitTube::recvObjects
    	| linux 体系调用 ::recv
  	| dispatchVsync
    	// env->CallVoidMethod 回到 JAVA 层的 DisplayEventReceiver.dispatchVsync() 
    	| DisplayEventReceiver.dispatchVsync()
      	// /frameworks/base/core/java/android/view/Choreographer.java
      	| FrameDisplayEventReceiver.onVsync
        		| Message msg = Message.obtain(mHandler, this);//传入的回调是this,即FrameDisplayEventReceiver.run() ;
        		| mHandler.sendMessageAtTime(msg, timestampNanos / TimeUtils.NANOS_PER_MS);
        		| 之后进入FrameDisplayEventReceiver.run()办法调用 doFrame 
          				| void doFrame(long frameTimeNanos, int frame, DisplayEventReceiver.VsyncEventData vsyncEventData)
            					| doCallbacks(Choreographer.CALLBACK_INPUT, frameTimeNanos, frameIntervalNanos)
            					| doCallbacks(Choreographer.CALLBACK_ANIMATION, frameTimeNanos, frameIntervalNanos);
            					| doCallbacks(Choreographer.CALLBACK_INSETS_ANIMATION, frameTimeNanos, frameIntervalNanos);
            					| doCallbacks(Choreographer.CALLBACK_TRAVERSAL, frameTimeNanos, frameIntervalNanos);
              							| ViewRootImpl.mTraversalRunnable.run()
                							| doTraversal();
                  								| performTraversals();
                    								|	relayoutWindow //创立 Surface 流程
            					| doCallbacks(Choreographer.CALLBACK_COMMIT, frameTimeNanos, frameIntervalNanos);

3、ViewRootImpl.relayoutWindow 创立 Surface

ViewRootImpl.mTraversalRunnable.run()
| doTraversal();
  | performTraversals(); 
	// 假如是ViewRootImpl刚创立,还没履行过performTraversals,或许窗口需求resize,或许显现特点改变,需求履行 relayoutWindow
    | relayoutWindow   //创立surface流程 + sf 创立layer流程
ViewRootImpl.relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,boolean insetsPending);
|	mWindowSession.relayout(mWindow, params,requestedWidth, requestedHeight,...mSurfaceControl, mTempInsets, mTempControls, mRelayoutBundle);
	|	// 【接口层:ViewRootImpl.mSurfaceControl 结构流程】
	|	android.view.IWindowSession.Stub.Proxy.relayout(...android.view.SurfaceControl outSurfaceControl,...)
        |	// 调用 system_server 进程 Session.relayout  【转到: "system_server 进程 Session.relayout"】
        |	boolean _status = mRemote.transact(Stub.TRANSACTION_relayout, _data, _reply, 0);
			|	//若干步骤太多了不写了QTNND...
			|	IPCThreadState::transact(...);
				|	IPCThreadState::waitForResponse(...);//binder通讯
		|	// 从 system_server 进程回来后,从 _reply 读取回来的 SurfaceControl 到 outSurfaceControl,即 ViewRootImpl.mSurfaceControl
		|	outSurfaceControl.readFromParcel(_reply); 
// system_server 进程 Session.relayout
|-->Session.relayout(IWindow window, WindowManager.LayoutParams attrs,...SurfaceControl outSurfaceControl,...)
    //进入system_server进程的 WMS
  	|	mService.relayoutWindow(this, window, attrs,requestedWidth, requestedHeight,... outSurfaceControl,...)
    |-->WindowManagerService.relayoutWindow(Session session, IWindow client, LayoutParams attrs,...SurfaceControl outSurfaceControl,...)
    	|	int result = 0;
    	|	//从 WindowManagerService.mWindowMap 获取之前addToDisplayAsUser流程存储的 WindowState
    	|	final WindowState win = windowForClientLocked(session, client, false);
		|	// WindowState.mWinAnimator: WindowState结构函数中创立的
		|	WindowStateAnimator winAnimator = win.mWinAnimator;
		|	result = createSurfaceControl(outSurfaceControl, result, win, winAnimator);
    	|-->WindowManagerService.createSurfaceControl(SurfaceControl outSurfaceControl, int result,WindowState win, WindowStateAnimator winAnimator)
            |	WindowSurfaceController surfaceController = winAnimator.createSurfaceLocked();
			|-->WindowStateAnimator.createSurfaceLocked()
                |	final WindowState w = mWin; // WindowState结构函数中会把WindowState自身传入WindowStateAnimator.mWin
				|	final WindowManager.LayoutParams attrs = w.mAttrs;
				|	final int format = isHwAccelerated ? PixelFormat.TRANSLUCENT : attrs.format;	
				|	// 1、创立 WindowSurfaceController,赋值到 WindowStateAnimator.mSurfaceController
        |		|	mSurfaceController = new WindowSurfaceController(attrs.getTitle().toString(), format, flags, this, attrs.type);
				//	WindowSurfaceController 结构函数
				|-->WindowSurfaceController(String name, int format, int flags, WindowStateAnimator animator,int windowType)	
                    |	mAnimator = animator; title = name; mService = animator.mService;
					|	final WindowState win = animator.mWin;
					|	mWindowType = windowType;
					|	mWindowSession = win.mSession;
					|	// 注意这儿的 parent = WindowState.mSurfaceControl
					|	SurfaceControl.Builder b = win.makeSurface().setParent(win.getSurfaceControl()).setName(name).setFormat(format)
                        .setFlags(flags).setMetadata(METADATA_WINDOW_TYPE, windowType).setMetadata(...mUid).setMetadata(...mPid)...;
					|	//mService.mUseBLAST = (settings get global  use_blast_adapter_vr == 1)
                        //global  settings 中没有设置这个 use_blast_adapter_vr 值的话,默认值为 true
                        //PRIVATE_FLAG_USE_BLAST 这个 flag 是在 ViewRootImpl.setview 设置的
                        //综上,useBLAST = true
					|	boolean useBLAST = mService.mUseBLAST && ((win.getAttrs().privateFlags& LayoutParams.PRIVATE_FLAG_USE_BLAST) != 0);
					|	if (useBLAST) b.setBLASTLayer();
						|	//	FX_SURFACE_BLAST = 0x00040000; 对应于  ISurfaceComposerClient.eFXSurfaceBufferState = 0x00040000
						|-->SurfaceControl.Builder.setFlags(FX_SURFACE_BLAST, FX_SURFACE_MASK); 
					|	// 2、创立Java层的 SurfaceControl ,赋值到 WindowStateAnimator.mSurfaceController.mSurfaceControl
        |  			|	mSurfaceControl = b.build();
        |  		|		|	new SurfaceControl(mSession, mName, mWidth, mHeight, mFormat, mFlags, mParent, mMetadata,mLocalOwnerView, mCallsite);
						|-->SurfaceControl(SurfaceSession session, String name, int w, int h, int format, int flags, SurfaceControl parent...)
					|		|	mName = name;mWidth = w;mHeight = h;mLocalOwnerView = localOwnerView;
							|	// 3、创立native层的 SurfaceControl,赋值到 WindowStateAnimator.mSurfaceController.mSurfaceControl.mNativeObject
        |    				|   mNativeObject = nativeCreate(session, name, w, h, format, flags,... metaParcel);
        |      	|	|		|   // /frameworks/base/core/jni/android_view_SurfaceControl.cpp
        |                	|-->nativeCreate(..., jobject sessionObj,jstring nameStr, jint w, jint h, jint format, jint flags, ...)
                |				|   sp<SurfaceComposerClient> client;
								|	client = android_view_SurfaceSession_getClient(env, sessionObj);
								|	sp<SurfaceControl> surface;// surface 作为引证参数传入
								|	client->createSurfaceChecked(String8(name.c_str()), w, h, format, &surface,flags, parentHandle...);
								|	// /frameworks/native/libs/gui/SurfaceComposerClient.cpp
                				|   SurfaceComposerClient.createSurfaceChecked(const String8& name,...,sp<SurfaceControl>* outSurface,...)
                |                   |	sp<IBinder> handle;
		|					|		|	sp<IGraphicBufferProducer> gbp;
				|	|				|	int32_t id = -1;
        |          					|	mClient->createSurface(name, w, h, format, flags, parentHandle,... &handle, &gbp, &id, &transformHint);   
                    					|	//surfaceflinger/Client.cpp
                |    		|			|	mFlinger->createLayer
        |           |  						|	// 进入SurfaceFlinger进程,创立layer流程 【转“SurfaceFlinger创立layer”章节】
                      						|	SurfaceFlinger::createLayer(name, this, w, h, format,... handle, gbp, parentHandle, outLayerId,...)  
        |       |  					|	*outSurface = new SurfaceControl(this, handle, gbp, id, w, h, format,...flags);
					|		|		|	// 4、运用SurfaceFlinger创立的 handle,GraphicBufferProducer,layerId 结构native层的 SurfaceControl
		|		|					|	// GraphicBufferProducer 图形buffer的生产者,handle用于layer毁掉时SurfaceFlinger端回调,和layer检索
									|	SurfaceControl(const sp<SurfaceComposerClient>& client, const sp<IBinder>& handle,
                            |                          const sp<IGraphicBufferProducer>& gbp, int32_t layerId,
        |       |                                      uint32_t w, uint32_t h, PixelFormat format, uint32_t transform,uint32_t flags)
                    |       |           |	: mClient(client), mHandle(handle), mGraphicBufferProducer(gbp), mTransformHint(transform) 
        |       |           |           |	  mWidth(w),mHeight(h),mFormat(format),mCreateFlags(flags) {}
							|	|	return reinterpret_cast<jlong>(surface.get());// 回来native创立的 SurfaceControl 
							|   // 假如native有 mBbqChild ,回来 mBbqChild.mHandle,不然直接回来native SurfaceControl.mHandle
        |    	|	|	|	|	mNativeHandle = nativeGetHandle(mNativeObject);/
				|	w.mInputWindowHandle.forceChange();	
				|	return mSurfaceController;
      	|	|	surfaceController.getSurfaceControl(outSurfaceControl);//====================!!!
			|-->WindowSurfaceController.getSurfaceControl(SurfaceControl outSurfaceControl)	
                |	// 传入的是 WindowState.mWinAnimator.mSurfaceController.mSurfaceControl
                |	// 5、把AMS创立的 SurfaceControl 数据,仿制给需求回来 App进程的目标 outSurfaceControl
                |	outSurfaceControl.copyFrom(mSurfaceControl, "WindowSurfaceController.getSurfaceControl");
				|-->SurfaceControl.copyFrom(@NonNull SurfaceControl other, String callsite)
                    |	// 几个重要成员仿制
                    |	mName = other.mName; mLocalOwnerView = other.mLocalOwnerView;
					|	mWidth = other.mWidth; mHeight = other.mHeight;
					|	// native层SurfaceControl仿制, 以及 mNativeObject、mNativeHandle 仿制
					|	assignNativeObject(nativeCopyFromSurfaceControl(other.mNativeObject), callsite);
						|-->nativeCopyFromSurfaceControl(JNIEnv* env, jclass clazz, jlong surfaceControlNativeObj) 
                            |	sp<SurfaceControl> surface(reinterpret_cast<SurfaceControl *>(surfaceControlNativeObj));
							|	// native 层创立新的 SurfaceControl
                                // 把 WindowState.mWinAnimator.mSurfaceController.mSurfaceControl.mNativeObject 数据仿制到新的 SurfaceControl 目标
							|	sp<SurfaceControl> newSurface = new SurfaceControl(surface);
								|-->SurfaceControl::SurfaceControl(const sp<SurfaceControl>& other)
                                    |	mClient = other->mClient; mHandle = other->mHandle;
									|	mGraphicBufferProducer = other->mGraphicBufferProducer;	
									|	mTransformHint = other->mTransformHint;	 mLayerId = other->mLayerId;
									|	mWidth = other->mWidth; mHeight = other->mHeight;
									|	mFormat = other->mFormat; mCreateFlags = other->mCreateFlags;
							|	return reinterpret_cast<jlong>(newSurface.get()); // 回来新的SurfaceControl地址到Java层的 outSurfaceControl
						|-->SurfaceControl.assignNativeObject(long nativeObject, String callsite)
                            |	mNativeObject = nativeObject; // 把native地址赋值到 SurfaceControl.mNativeObject
							|	//这儿不展开了,没有mBbqChild,仍是运用 WindowState.mWinAnimator.mSurfaceController.mSurfaceControl.mNativeObject.mHandle
							|	mNativeHandle = nativeGetHandle(nativeObject);
			|	return result; // END  WindowManagerService.createSurfaceControl
			|	
		|	mWindowPlacerLocked.performSurfacePlacement(true /* force */); // 履行 Surface 的摆放作业
		|	// 假如焦点改变了更新焦点
		|	updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, true /*updateInputWindows*/)	
// 回到 APP进程端:ViewRootImpl.relayoutWindow            
//(1) 非 useBLAST 的状况:(Android12今后代码不会走这儿)
|	//6、创立 Surface          
|	mSurface.copyFrom(mSurfaceControl); 
|-->Surface.copyFrom(SurfaceControl other)
    |	long surfaceControlPtr = other.mNativeObject;
	|	// 获取 native 层的 Surface 地址
    |	long newNativeObject = nativeGetFromSurfaceControl(mNativeObject, surfaceControlPtr);
	|-->nativeGetFromSurfaceControl(JNIEnv* env, jclass clazz,jlong nativeObject, jlong surfaceControlNativeObj)
        |	sp<SurfaceControl> ctrl(reinterpret_cast<SurfaceControl *>(surfaceControlNativeObj));	
		|	sp<Surface> surface(ctrl->getSurface());// 创立native Surface
		|-->SurfaceControl.getSurface()
			|	return generateSurfaceLocked(); 
			|-->SurfaceControl.generateSurfaceLocked()
				|	// Android 11版别曾经,这个函数内部直接创立 Surface 回来:new Surface(mGraphicBufferProducer, false);
                |	// Android 12 这儿运用 BBQ ,还从这儿衔接 SurfaceFlinger 创立layer。ViewRootImpl不走这儿,现在这儿的流程不知道给谁用的
				|	mBbqChild = mClient->createSurface(String8("bbq-wrapper"), 0, 0, mFormat,flags, mHandle, {}, &ignore);
                |	// 以下流程展开参阅【创立Surface:useBLAST】章节   
				|	mBbq = sp<BLASTBufferQueue>::make("bbq-adapter", mBbqChild, mWidth, mHeight, mFormat);
				|	mSurfaceData = mBbq->getSurface(true); // 回来 new BBQSurface
				|	return mSurfaceData;
		|	surface->incStrong(&sRefBaseOwner);
		|	return reinterpret_cast<jlong>(surface.get());//回来 native 的 Surface 地址
    |	updateNativeObject(newNativeObject)
	|-->updateNativeObject(long newNativeObject)	
		|	setNativeObjectLocked(newNativeObject);
		|-->setNativeObjectLocked(long ptr)
			|	mNativeObject = ptr;// 把新的native的Surface地址存储到 Surface.mNativeObject
//(2)	useBLAST 的状况:(Android13 代码走这儿,在Android12的基础上略微改变了一下)
|	updateBlastSurfaceIfNeeded(); 
	|	mBlastBufferQueue = new BLASTBufferQueue(mTag, mSurfaceControl, mSurfaceSize.x, mSurfaceSize.y, mWindowAttributes.format);
	|	mBlastBufferQueue.setTransactionHangCallback(sTransactionHangCallback);
	|	Surface blastSurface = mBlastBufferQueue.createSurface();
	|	mSurface.transferFrom(blastSurface);
创立Surface:useBLAST (BBQ)

接续上一章节“useBLAST 的状况”

// frameworks/base/core/java/android/view/ViewRootImpl.java
// useBLAST 函数:
	/*	
	mForceDisableBLAST 运用默认值false
	mUseBLASTAdapter:假如 WMS.addWindow 回来值带有flag WindowManagerGlobal.ADD_FLAG_USE_BLAST ,则为 true。[见:IWindowSession.addToDisplayAsUser]
	Android 12 后有这个flag	
	*/
    boolean useBLAST() {
        return mUseBLASTAdapter && !mForceDisableBLAST;
    }
// 假如 useBLAST() 回来 true,则调用 updateBlastSurfaceIfNeeded(); 
// 接续上一章节“useBLAST 的状况”
// frameworks/base/core/java/android/view/ViewRootImpl.java
updateBlastSurfaceIfNeeded(); 
|	// 【1】创立 BLASTBufferQueue
|	// 参数:mSurfaceControl 是在 ViewRootImpl.mWindowSession.relayout 的接口层调用 mSurfaceControl.readFromParcel 填充的数据
|	mBlastBufferQueue = new BLASTBufferQueue(mTag, mSurfaceControl, mSurfaceSize.x, mSurfaceSize.y, mWindowAttributes.format);
|	// Java层 BLASTBufferQueue 结构
|-->BLASTBufferQueue (String name, SurfaceControl sc, int width, int height, @PixelFormat.Format int format)
    |	mNativeObject = nativeCreate(name, true);// 创立 native 层 BLASTBufferQueue,回来的地址存储到 mNativeObject
	|	//【2】创立 native BLASTBufferQueue
    |	//frameworks/base/core/jni/android_graphics_BLASTBufferQueue.cpp 
	|-->nativeCreate(JNIEnv* env, jclass clazz, jstring jName, jboolean updateDestinationFrame)
        |	sp<BLASTBufferQueue> queue = new BLASTBufferQueue(name.c_str(), updateDestinationFrame);
		|	// native 层 BLASTBufferQueue 结构,Android 13的结构函数比较 Android 12 少了一部分内容,那部分内容放到了 BLASTBufferQueue::update
		|-->BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinationFrame)
            |	: mSurfaceControl(nullptr),mSize(1, 1),mRequestedSize(mSize),mFormat(PIXEL_FORMAT_RGBA_8888),
			|		mTransactionReadyCallback(nullptr),mSyncTransaction(nullptr),mUpdateDestinationFrame(updateDestinationFrame){
            |	// 【3】创立 BufferQueueCore、BBQBufferQueueProducer、BufferQueueConsumer     
            |	createBufferQueue(&mProducer, &mConsumer); //[转 BLASTBufferQueue::createBufferQueue  章节]
                // BufferQueueProducer.mDequeueTimeout = int64.max
            |	mProducer->setDequeueTimeout(std::numeric_limits<int64_t>::max());    
                /*
                BufferQueueCore:
    				std::set<int> mFreeSlots;  	  // 初始增加 2个int
    				std::list<int> mUnusedSlots;  // 初始增加 64 int值
                setMaxDequeuedBufferCount(2)的成果:
                	1)从 BufferQueueCore.mUnusedSlots 中取出 1 个并删去,然后刺进 BufferQueueCore.mFreeSlots;
                	   mUnusedSlots 长度变为 63,mFreeSlots长度变为 3
                       (mFreeSlots,是dequeuebuffer数据来历,其长度代表最大可dequeue的数量,当时为3,表明三级缓存)
                	2)BufferQueueCore.mMaxDequeuedBufferCount = 2; BufferQueueCore.mMaxAcquiredBufferCount = 1;
                	3)调整结束mMaxDequeuedBufferCount后,假如 dequeueBuffer 处于等候buffer状况,会被唤醒拿取buffer
                函数调用完结后,假如调用 getMaxBufferCountLocked,在同步形式下:
                	BufferQueueCore.getMaxBufferCountLocked() = mMaxDequeuedBufferCount + mMaxAcquiredBufferCount = 3 (三级缓存)
                */
            |	mProducer->setMaxDequeuedBufferCount(2);  
            |	// 【4】创立 BLASTBufferItemConsumer 并设置生产者顾客监听   
            |	mBufferItemConsumer = new BLASTBufferItemConsumer(mConsumer,USAGE_HW_COMPOSER|USAGE_HW_TEXTURE, 1, false, this);
            |-->BLASTBufferItemConsumer(IGBConsumer& consumer,uint64_t consumerUsage,int bufferCount, bool controlledByApp, wp<BLASTBufferQueue> bbq)
                	: BufferItemConsumer(consumer, consumerUsage, bufferCount, controlledByApp),//结构父类BufferItemConsumer
                	  mBLASTBufferQueue(std::move(bbq)),/* 存储 BBQ*/mCurrentlyConnected(false),mPreviouslyConnected(false) {}
                |-->:BufferItemConsumer(sp<IGraphicBufferConsumer>& consumer,uint64_t consumerUsage,int bufferCount, bool controlledByApp)
                    	: ConsumerBase(consumer, controlledByApp){
                            // BufferQueueCore.mConsumerUsageBits = GraphicBuffer::USAGE_HW_COMPOSER |GraphicBuffer::USAGE_HW_TEXTURE;
                            mConsumer->setConsumerUsageBits(consumerUsage);
                            // 默认 BufferQueueCore->mMaxAcquiredBufferCount = 1,bufferCount=1, 所以这儿无用功
                            mConsumer->setMaxAcquiredBufferCount(bufferCount);
                        }
                	|-->ConsumerBase.ConsumerBase(const sp<IGraphicBufferConsumer>& bufferQueue, bool controlledByApp)
                        	: mAbandoned(false),mConsumer(bufferQueue),mPrevFinalReleaseFence(Fence::NO_FENCE){
                                // 创立未命令的姓名,这儿的姓名会被之后 BLASTBufferQueue 结构函数的代码覆盖
                                mName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
                                wp<ConsumerListener> listener = static_cast<ConsumerListener*>(this);
                                sp<IConsumerListener> proxy = new BufferQueue::ProxyConsumerListener(listener);
                                //【5】调用顾客的 connect 函数,这儿的代码履行成果:
                                // 1、赋值 BufferQueueCore 的顾客监听: BufferQueueCore.mConsumerListener = ConsumerBase
                                // 2、BufferQueueCore.mConsumerControlledByApp = false
                                status_t err = mConsumer->consumerConnect(proxy, controlledByApp);
                                mConsumer->setConsumerName(mName);// 姓名传给 BufferQueueConsumer、BufferQueueCore
                            }
            //	consumerName = "ViewRootImpl#[id](BLAST Consumer)[id]"    
            //BufferQueueCore.mConsumerName = BufferQueueConsumer.mConsumerName = BufferItemConsumer父类ConsumerBase.mName = consumerName;    
            |	mBufferItemConsumer->setName(String8(consumerName.c_str()));    
                //	ConsumerBase.mFrameAvailableListener =  BLASTBufferQueue
            |	mBufferItemConsumer->setFrameAvailableListener(this); // queuebuffer后,告诉顾客的监听
                //	BufferItemConsumer.mBufferFreedListener =  BLASTBufferQueue
            |	mBufferItemConsumer->setBufferFreedListener(this);    // 告诉生产者的的监听
            |	ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers);// 从是sf获取MaxAcquiredBufferCount
                // 赋值 sf 的MaxAcquiredBufferCount
            |	mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers);
            |	mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers;    
            |}	
		|	return reinterpret_cast<jlong>(queue.get());// 回来 native BLASTBufferQueue 地址
	|	nativeUpdate(mNativeObject, sc.mNativeObject, width, height, format);
	|-->nativeUpdate(JNIEnv* env, jclass clazz, jlong ptr, jlong surfaceControl, jlong width,jlong height, jint format)
        |	sp<BLASTBufferQueue> queue = reinterpret_cast<BLASTBufferQueue*>(ptr);
		|	queue->update(reinterpret_cast<SurfaceControl*>(surfaceControl), width, height, format);
		|-->BLASTBufferQueue.update(const sp<SurfaceControl>& surface, uint32_t width, uint32_t height,int32_t format)
            |	// 这些值,在 BufferQueueProducer::connect 函数中,会再回来 Surface
            |	mFormat = format;										BufferQueueCore->mDefaultBufferFormat = mFormat;
			|	mSurfaceControl = surface;
			|	mTransformHint = mSurfaceControl->getTransformHint();	BufferQueueCore->mTransformHint = mTransformHint;
			|	// 这儿的宽高,来历是 ViewRootImpl.relayout 后经过 WindowLayout::computeSurfaceSize 计算的宽高
			|	mRequestedSize = newSize(width, height);
			|	mSize = mRequestedSize;	
			|	BufferQueueCore->mDefaultWidth = mRequestedSize.width;	BufferQueueCore->mDefaultHeight = mRequestedSize.height;
			|	//之后再把 宽高 经过业务传递到sf
            |	SurfaceComposerClient::Transaction.setApplyToken(mApplyToken).apply(false, true);    
|	mBlastBufferQueue.setTransactionHangCallback(sTransactionHangCallback);// GPU hang 回调	
|	Surface blastSurface = mBlastBufferQueue.createSurface();
|	|	BlastBufferQueue.nativeGetSurface(mNativeObject, false /* includeSurfaceControlHandle */);
	|	//frameworks/base/core/jni/android_graphics_BLASTBufferQueue.cpp
	|-->nativeGetSurface(JNIEnv* env, jclass clazz, jlong ptr, jboolean includeSurfaceControlHandle)
        |	sp<BLASTBufferQueue> queue = reinterpret_cast<BLASTBufferQueue*>(ptr); // 地址转为 native BLASTBufferQueue 目标
		|	return android_view_Surface_createFromSurface(env,queue->getSurface(includeSurfaceControlHandle));
			|	//	【6】创立 BBQSurface
			|	//frameworks/native/libs/gui/BLASTBufferQueue.cpp
            |-->BLASTBufferQueue.getSurface(bool includeSurfaceControlHandle) 
                |	sp<IBinder> scHandle = nullptr;
				|	if (includeSurfaceControlHandle && mSurfaceControl)// includeSurfaceControlHandle = false
                    |	scHandle = mSurfaceControl->getHandle();
                |	return new BBQSurface(mProducer, true, scHandle, this);
				|	//创立 BBQSurface,比较重要的是重载了 allocateBuffers 
				|-->BBQSurface(const sp<IGraphicBufferProducer>& igbp, bool controlledByApp,
               			const sp<IBinder>& scHandle, const sp<BLASTBufferQueue>& bbq)
          				: Surface(igbp, controlledByApp, scHandle), mBbq(bbq) {}	
					|	//Surface 的结构函数内容太多了不写了
                    |-->Surface::Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp,...)
                        : mGraphicBufferProducer(bufferProducer) // 最要害的便是传入了 生产者
                            |	mProducerControlledByApp = controlledByApp; // true
			|	// 【7】创立Java层的 Surface,并把 BBQSurface 的地址存入Surface.mNativeObject,(这一步便是创立个java的Surface,暂时存储native的BBQSurface)
			|	//frameworks/base/core/jni/android_view_Surface.cpp
            |-->android_view_Surface_createFromSurface(JNIEnv* env, const sp<Surface>& surface)
                |	// 在 JNI new Java 层的 Surface 	
                |	jobject surfaceObj = env->NewObject(gSurfaceClassInfo.clazz, gSurfaceClassInfo.ctor, (jlong)surface.get());
				|	// 调用Java层,参数为 long 的结构函数:
				|-->Surface(long nativeObject)
                    |	setNativeObjectLocked(nativeObject);
						|	mNativeObject = nativeObject;
				|	return surfaceObj;	// 回来java层的目标
|	//【8】把回来的BBQSurface地址 Surface.mNativeObject 转存入 ViewRootImpl.mSurface.mNativeObject
|	mSurface.transferFrom(blastSurface); // mSurface.mNativeObject = blastSurface.mNativeObject

4、BLASTBufferQueue::createBufferQueue 生产者-顾客-BufferQueueCore

//	frameworks/native/libs/gui/BLASTBufferQueue.cpp
BLASTBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer, sp<IGraphicBufferConsumer>* outConsumer)
|	// 1、创立 BufferQueueCore
|	sp<BufferQueueCore> core(new BufferQueueCore());
	|	// BufferQueueCore 结构函数:
	|-->BufferQueueCore::BufferQueueCore()
          : mMutex(), mConsumerControlledByApp(false), 
		    mSlots(),	    // BufferSlot[64] mSlots; 创立 Slots
		    mQueue(),	    // Vector<BufferItem>  mQueue;   queuebuffer 后存储到这个变量里
			// FREE 状况,没有GraphicBuffer的放到mFreeSlots里
			mFreeSlots(),   // std::set<int> mFreeSlots;  初始化为 2个int, mUnusedSlots 每减一个,对应的 mFreeSlots 参加一个
			// FREE 状况,可是有buffer attached
			mFreeBuffers(), // std::list<int> mFreeBuffers;
			// 未被运用的 Slot ,开端长度为64,64 + 2个mFreeSlots的元素 其实代表了 Slot 的总数
			// 依据 adjustAvailableSlotsLocked函数,可以得出 mUnusedSlots 每减一个,对应的 mFreeSlots 参加一个(参加的便是mUnusedSlots减去的那个)
			mUnusedSlots(), // std::list<int> mUnusedSlots;
			// 当运用申请走一个Slot时,该Slot状况会切换到DEQUEUED状况,该Slot会被放入mActiveBuffers行列
			mActiveBuffers(),//std::set<int> mActiveBuffers;
			// mutable std::condition_variable mDequeueCondition;
			mDequeueCondition(), // dequeueBuffer 没slot时,调用 mDequeueCondition.wait 等候
			mDequeueBufferCannotBlock(false), // bool mDequeueBufferCannotBlock = false; dequeueBuffer 时 阻塞
			mQueueBufferCanDrop(false), mLegacyBufferDrop(true), mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888),/*默认运用的格式*/
			mDefaultWidth(1), mDefaultHeight(1), mDefaultBufferDataSpace(HAL_DATASPACE_UNKNOWN),
			mMaxBufferCount(BufferQueueDefs::NUM_BUFFER_SLOTS), // NUM_BUFFER_SLOTS = 64; 这个值64,设置这么大其实用多少
			mMaxAcquiredBufferCount(1),  mMaxDequeuedBufferCount(1),...
            mTransformHint(0)/*优化屏幕旋转*/,mIsAllocating(false)/*是否正在分配内存*/,mIsAllocatingCondition(),
			mAllowAllocation(true),  /*允许分配新buffer, BufferQueueProducer::connect时,设置为true*/
            mBufferAge(0),/*当时的 BufferSlot 自从前次 queueBuffer 后,又queue了多少个BufferSlot*/
            mAsyncMode(false),/*同步形式*/ mSharedBufferMode(false),...
            mUniqueId(getUniqueId()),mAutoPrerotation(false)/*主动预旋转*/,mTransformHintInUse(0)/*主动预旋转的方向,90度时宽高交换*/{
                int numStartingBuffers = getMaxBufferCountLocked(); //numStartingBuffers  = 2
                // 结构函数中 set<int> mFreeSlots 刺进两个int
                for (int s = 0; s < numStartingBuffers; s++) {
                    mFreeSlots.insert(s);
                }
                // 结构函数中 std::list<int> mUnusedSlots 刺进 64 个int
                for (int s = numStartingBuffers; s < BufferQueueDefs::NUM_BUFFER_SLOTS; s++) { // NUM_BUFFER_SLOTS = 64
                    mUnusedSlots.push_front(s); 
                }
            }
|	// 2、创立生产者
|	sp<IGraphicBufferProducer> producer(new BBQBufferQueueProducer(core, this));
	|	// BBQBufferQueueProducer 没多少内容,便是重载了 connect、setMaxDequeuedBufferCount、query
	|-->BBQBufferQueueProducer(const sp<BufferQueueCore>& core, wp<BLASTBufferQueue> bbq)
        // mConsumerIsSurfaceFlinger 入队后,GraphicBuffer 在BufferItem 中的指针是否应该被清除
        : BufferQueueProducer(core, false /* consumerIsSurfaceFlinger*/),mBLASTBufferQueue(std::move(bbq)) {}	
		|-->BufferQueueProducer::BufferQueueProducer(const sp<BufferQueueCore>& core, bool consumerIsSurfaceFlinger) 
            : mCore(core), mSlots(core->mSlots), mConsumerName(),mStickyTransform(0),
			  mConsumerIsSurfaceFlinger(consumerIsSurfaceFlinger/*false*/),mLastQueueBufferFence(Fence::NO_FENCE),mLastQueuedTransform(0),
			  mCallbackMutex(),mNextCallbackTicket(0),mCurrentCallbackTicket(0),mCallbackCondition(),
			  mDequeueTimeout(-1),mDequeueWaitingForAllocation(false) {}
|	// 3、创立顾客
|	sp<BufferQueueConsumer> consumer(new BufferQueueConsumer(core));
	|-->BufferQueueConsumer::BufferQueueConsumer(const sp<BufferQueueCore>& core)
        : mCore(core), mSlots(core->mSlots), mConsumerName() {}
|	// 4、生产顾客赋值到 BLASTBufferQueue成员变量 mProducer 和 mConsumer
|	*outProducer = producer;
|	*outConsumer = consumer;

七、SurfaceFlinger创立layer

Android 11 以及曾经的版别简述:

SurfaceFlinger::createLayer
| SurfaceFlinger::createBufferQueueLayer(client, uniqueName, w, h, flags, metadata, format, handle, gbp, &layer);
  | sp<BufferQueueLayer> layer;
  | layer = getFactory().createBufferQueueLayer(args);
    | BufferQueueLayer 目标创立完结后,在初次sp指针引证时调用 BufferQueueLayer::onFirstRef()
      | onFirstRef函数中会创立 生产者,顾客,生产者会传入到客户端
      | sp<IGraphicBufferProducer> producer;
      | sp<IGraphicBufferConsumer> consumer;
      | 设置生产者的三级缓冲
      | mProducer->setMaxDequeuedBufferCount(2);
  | 赋值client端的参数 
  | sp<IBinder> *handle = layer->getHandle();
  | sp<IGraphicBufferProducer> *gbp = layer->getProducer(); //获取生产者
  | sp<Layer> *outLayer = layer; //这个layer保存在 SurfaceComposerClient目标中,wms并未赋值,wms对应的是SurfaceControl
| addClientLayer
  | 调用 addClientLayer,把layer依照Z轴顺序存入 layersSortedByZ

SurfaceFlinger::createLayer Android 13

  • Android 12 今后由于BBQ都在APP进程,所以 createLayer 大大简化了,内容不多。
【接续“ViewRootImpl.relayoutWindow 创立 Surface” 章节中的 “SurfaceComposerClient.createSurfaceChecked”】
SurfaceFlinger::createLayer(LayerCreationArgs& args, sp<IBinder>* outHandle,sp<IBinder>& parentHandle, int32_t* outLayerId, sp<Layer>& parentLayer, uint32_t* outTransformHint)
|	sp<Layer> layer;    
|	switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask){
        case ISurfaceComposerClient::eFXSurfaceBufferQueue:
         /*
         eFXSurfaceBufferState = 0x00040000
         WindowManagerService.createSurfaceControl 流程中 
         	if (useBLAST) b.setBLASTLayer(); 这个函数设置的flag FX_SURFACE_BLAST = 0x00040000;
         */
        case ISurfaceComposerClient::eFXSurfaceBufferState:
        	result = createBufferStateLayer(args, outHandle, &layer);
        	|	createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle, sp<Layer>* outLayer)
                |	*outLayer = getFactory().createBufferStateLayer(args); // 创立的 layer 
        			|-->BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
                        |	: BufferLayer(args), mHwcSlotGenerator(new HwcSlotGenerator())
                        |   mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
        					|-->BufferLayer::BufferLayer(const LayerCreationArgs& args)
                                	: Layer(args), mTextureName(args.textureName),
        						|	mCompositionState{mFlinger->getCompositionEngine().createLayerFECompositionState()} 
        						|-->Layer::Layer(const LayerCreationArgs& args)
                                    	: sequence(args.sequence.value_or(sSequence++)),
        								  mFlinger(args.flinger),
        								  mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)),
        								  mClientRef(args.client),
        								  mWindowType(static_cast<WindowInfo::Type>(args.metadata.getInt32(METADATA_WINDOW_TYPE, 0))),
        								  mLayerCreationFlags(args.flags)
                                         // 然后是一堆 mDrawingState 成员特点的初始化     	
        		|	*handle = (*outLayer)->getHandle(); // 把创立的 handle 传入外部,终究会回来到APP进程端,用于创立 SurfaceControl
        break;
        case ISurfaceComposerClient::eFXSurfaceEffect: // 这儿是 Task、DefaultTaskDisplayArea
        	result = createEffectLayer(args, outHandle, &layer);
        	break;
        case ISurfaceComposerClient::eFXSurfaceContainer://这儿是 ActivityRecord、WindowState 等等
        	result = createContainerLayer(args, outHandle, &layer);
        	break;
        default:
        	result = BAD_VALUE;
        break;	
	}
|		
|	result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
|-->SurfaceFlinger.addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,const sp<Layer>& layer, const wp<Layer>& parent,...)
    |	//	std::vector<LayerCreatedState> mCreatedLayers  参加到数组
    |	mCreatedLayers.emplace_back(layer, parent, addToRoot);
	|	//	缓存到 Client.mLayers 调集中 //frameworks/native/services/surfaceflinger/Client.h
	|	client->attachLayer(handle, layer);
    |	// 恳求 sf-vsync,这儿的代码和 SurfaceFlinger::commitCreatedLayers() 以及 mCreatedLayers 是相相关的,详细见 SurfaceFlinger 章节
	|	setTransactionFlags(eTransactionNeeded);
|	*outLayerId = layer->sequence;
|	return result;