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

4,037 阅读31分钟

Android图形显示系统.png

注:

  • 本文基于 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;