Android 11.0源码系列之WMSWindowManagerService
Posted bubbleben
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 11.0源码系列之WMSWindowManagerService相关的知识,希望对你有一定的参考价值。
本篇涉及到的主要代码:
frameworks\\base\\services\\core\\java\\com\\android\\server\\SystemServer.java
frameworks\\base\\services\\core\\java\\com\\android\\server\\wm\\WindowManagerService.java
frameworks\\base\\services\\core\\java\\com\\android\\server\\wm\\WindowAnimator.java
frameworks\\base\\services\\core\\java\\com\\android\\server\\AnimationThread.java
frameworks\\base\\core\\java\\android\\view\\Choreographer.java
frameworks\\base\\services\\core\\java\\com\\android\\server\\wm\\RootWindowContainer.java
frameworks\\base\\services\\core\\java\\com\\android\\server\\wm\\SurfaceAnimationRunner.java
frameworks\\base\\services\\core\\java\\com\\android\\server\\wm\\SurfaceAnimationThread.java
众所周知Android系统框架提供了众多的系统服务,比如管理四大组件的AMS
(ActivityManagerService
),管理窗口的WMS
(WindowManagerService
),管理应用安装, 卸载和更新的PMS
(PackageManagerService
),管理输入事件和输入设备的IMS
(InputManagerService
)等等,本系列将基于Android 11.0.0_r1
代码,从上到下(java->jni->native
)对这几大服务进行逐一解读,旨在加深对Android
整个体系结构的理解,了解框架层各组件的运行原理,为以后深入性能分析/系统优化/架构设计等打下坚实的基础。
1.1 WindowManagerService的创建
与InputManagerService
一样,WindowManagerService
也是在startOtherServices
阶段,由SystemServer
创建并以window
为别名添加到ServiceManager
中;
[-> SystemServer.java]
private void startOtherServices(@NonNull TimingsTraceAndSlog t)
InputManagerService inputManager = null;
// 初始化InputManagerService
inputManager = new InputManagerService(context);
WindowManagerService wm = null;
// 初始化WindowManagerService[见1.2小节]
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
// 将WindowManagerServic添加到ServiceManager
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
// 将WindowManagerService保存到AMS和ATMS
mActivityManagerService.setWindowManager(wm);
// WindowManagerService初始化[见1.3小节]
wm.onInitReady();
// 为InputManagerService设置WindowManagerCallbacks
inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
try
// 更新Display相关配置[见1.4小节]
wm.displayReady();
catch (Throwable e)
reportWtf("making display ready", e);
try
// 系统启动完成[见1.5小节]
wm.systemReady();
catch (Throwable e)
reportWtf("making Window Manager Service ready", e);
// Update the configuration for this context by hand, because we're going
// to start using it before the config change done in wm.systemReady() will
// propagate to it.
final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY);
DisplayMetrics metrics = new DisplayMetrics();
context.getDisplay().getMetrics(metrics);
context.getResources().updateConfiguration(config, metrics);
1.2 WindowManagerService的构造
[-> WindowManagerService.java]
public static WindowManagerService main(final Context context, final InputManagerService im,
final boolean showBootMsgs, final boolean onlyCore, WindowManagerPolicy policy,
ActivityTaskManagerService atm)
return main(context, im, showBootMsgs, onlyCore, policy, atm,
SurfaceControl.Transaction::new, Surface::new, SurfaceControl.Builder::new);
main
会传入InputManagerService
和ActivityTaskManagerService
,其中ActivityTaskManagerService
是在startBootstrapServices
阶段创建的;
PhoneWindowManager
作为WindowManagerPolicy
的实现类,主要用于窗口策略的管理;
SurfaceControl.Transaction
和Surface
通过lambda
表达式生成Supplier
用于返回对应的实例;
SurfaceControl.Builder
通过lambda
表达式生成Function
接收SurfaceSession
参数并返回SurfaceControl.Builder
实例;
public static WindowManagerService main(final Context context, final InputManagerService im,
final boolean showBootMsgs, final boolean onlyCore, WindowManagerPolicy policy,
ActivityTaskManagerService atm, Supplier<SurfaceControl.Transaction> transactionFactory,
Supplier<Surface> surfaceFactory,
Function<SurfaceSession, SurfaceControl.Builder> surfaceControlFactory)
DisplayThread.getHandler().runWithScissors(() ->
sInstance = new WindowManagerService(context, im, showBootMsgs, onlyCore, policy,
atm, transactionFactory, surfaceFactory, surfaceControlFactory), 0);
return sInstance;
当前为system_server
主线程,通过runWithScissors
在android.display
线程创建WindowManagerService
:runWithScissors
区别于普通post
方法在于它是同步的:如果当前线程与Handler
所在线程为同一线程,则直接执行Runnable
,否则将Runnable
post
到Handler
所在线程的消息队列,然后通过wait()
等待它的完成,如果Runnable
执行完则直接返回否则阻塞,这样做的目的在于WindowManagerService
作为图形化窗口的管理者,如果未启动完成则后续的工作就无从谈起,所以这里必须同步阻塞直到它完成初始化构造;
/** Global service lock used by the package the owns this service. */
final WindowManagerGlobalLock mGlobalLock;
final InputManagerService mInputManager;
final DisplayManagerInternal mDisplayManagerInternal;
final DisplayManager mDisplayManager;
final ActivityTaskManagerService mAtmService;
WindowManagerPolicy mPolicy;
Function<SurfaceSession, SurfaceControl.Builder> mSurfaceControlFactory;
Supplier<SurfaceControl.Transaction> mTransactionFactory;
final Supplier<Surface> mSurfaceFactory;
private final SurfaceControl.Transaction mTransaction;
// The root of the device window hierarchy.
RootWindowContainer mRoot;
final WindowAnimator mAnimator;
SurfaceAnimationRunner mSurfaceAnimationRunner;
private WindowManagerService(Context context, InputManagerService inputManager,
boolean showBootMsgs, boolean onlyCore, WindowManagerPolicy policy,
ActivityTaskManagerService atm, Supplier<SurfaceControl.Transaction> transactionFactory,
Supplier<Surface> surfaceFactory,
Function<SurfaceSession, SurfaceControl.Builder> surfaceControlFactory)
// system_server公用的一把锁,主要用于ATMS和WMS
mGlobalLock = atm.getGlobalLock();
// 保存ActivityTaskManagerService
mAtmService = atm;
// 保存InputManagerService
mInputManager = inputManager; // Must be before createDisplayContentLocked.
// 获取供system_server内部调用的LocalService
mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
// 保存Supplier和Function
mSurfaceControlFactory = surfaceControlFactory;
mTransactionFactory = transactionFactory;
mSurfaceFactory = surfaceFactory;
// 获取SurfaceControl.Transaction实例
mTransaction = mTransactionFactory.get();
// 保存PhoneWindowManager
mPolicy = policy;
// 创建WindowAnimator[见1.2.1小节]
mAnimator = new WindowAnimator(this);
// 创建RootWindowContainer[见1.2.2小节]
mRoot = new RootWindowContainer(this);
// 将PhoneWindowManager用于system_server内部调用
LocalServices.addService(WindowManagerPolicy.class, mPolicy);
// 获取DisplayManager
mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
// 创建SurfaceAnimationRunner[见1.2.3小节]
mSurfaceAnimationRunner = new SurfaceAnimationRunner(mTransactionFactory,
mPowerManagerInternal);
// 将内部类LocalService用于system_server内部调用
LocalServices.addService(WindowManagerInternal.class, new LocalService());
WindowManagerService
的构造函数主要创建了与窗口动画,窗口管理,Surface
管理等相关的类;
1.2.1 WindowAnimator的创建
[-> WindowAnimator.java]
/**
* Singleton class that carries out the animations and Surface operations in a separate task
* on behalf of WindowManagerService.
*/
public class WindowAnimator
final Choreographer.FrameCallback mAnimationFrameCallback;
private Choreographer mChoreographer;
WindowAnimator(final WindowManagerService service)
// 调用WindowManagerService的mAnimationHandler同步获取Choreographer[见1.2.1.1小节]
service.mAnimationHandler.runWithScissors(
// 获取SF Choreographer[见1.2.1.2小节]
() -> mChoreographer = Choreographer.getSfInstance(), 0 /* timeout */);
// 实现FrameCallback接口
mAnimationFrameCallback = frameTimeNs ->
synchronized (mService.mGlobalLock)
mAnimationFrameCallbackScheduled = false;
animate(frameTimeNs);
if (mNotifyWhenNoAnimation && !mLastRootAnimating)
mService.mGlobalLock.notifyAll();
;
WindowAnimator
主要用于代表WindowManagerService
在独立的线程执行窗口动画和Surface
相关的操作:这个单独的线程就是AnimationThread
,同时动画的执行与Input
事件(CALLBACK_INPUT
)和界面绘制(CALLBACK_TRAVERSAL
)等一样,都依赖于vsync-app
信号的到来并通过CALLBACK_ANIMATION
回调来执行;
1.2.1.1 AnimationThread的创建
[-> WindowManagerService.java]
/**
* Handler for things to run that have direct impact on an animation, i.e. animation tick,
* layout, starting window creation, whereas @link H runs things that are still important, but
* not as critical.
*/
final Handler mAnimationHandler = new Handler(AnimationThread.getHandler().getLooper());
[-> AnimationThread.java]
/**
* Thread for handling all legacy window animations, or anything that's directly impacting
* animations like starting windows or traversals.
*/
public final class AnimationThread extends ServiceThread
private static AnimationThread sInstance;
private static Handler sHandler;
private AnimationThread()
super("android.anim", THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
mAnimationHandler
绑定的是android.anim
线程,与之对应的是android.anim.lf
线程SurfaceAnimationThread
;
1.2.1.2 Choreographer的获取
[-> Choreographer.java]
// Thread local storage for the SF choreographer.
private static final ThreadLocal<Choreographer> sSfThreadInstance =
new ThreadLocal<Choreographer>()
@Override
protected Choreographer initialValue()
Looper looper = Looper.myLooper();
if (looper == null)
throw new IllegalStateException("The current thread must have a looper!");
return new Choreographer(looper, VSYNC_SOURCE_SURFACE_FLINGER);
;
public static Choreographer getSfInstance()
return sSfThreadInstance.get();
通过ThreadLocal
存储的sSfThreadInstance
与 sThreadInstance
的区别在于它是用于监听vsync-sf
信号而sThreadInstance
是用于监听vsync-app
信号;
1.2.2 RootWindowContainer的创建
[-> RootWindowContainer.java]
/** Root @link WindowContainer for the device. */
class RootWindowContainer extends WindowContainer<DisplayContent>
implements DisplayManager.DisplayListener
ActivityStackSupervisor mStackSupervisor;
// Only a separate transaction until we separate the apply surface changes
// transaction from the global transaction.
private final SurfaceControl.Transaction mDisplayTransaction;
private final Handler mHandler;
RootWindowContainer(WindowManagerService service)
super(service);
mDisplayTransaction = service.mTransactionFactory.get();
// 绑定WindowManagerService.mH所在的线程
mHandler = new MyHandler(service.mH.getLooper());
mService = service.mAtmService;
mStackSupervisor = mService.mStackSupervisor;
mStackSupervisor.mRootWindowContainer = this;
RootWindowContainer
作为窗口容器在树结构中的根节点用来保存DisplayContent
;
[-> WindowManagerService.java]
final H mH = new H();
mHandler
与system_server
主线程绑定在同一个线程;
1.2.3 SurfaceAnimationRunner的创建
[-> SurfaceAnimationRunner.java]
/**
* Class to run animations without holding the window manager lock.
*/
class SurfaceAnimationRunner
// 获取android.anim线程的Handler
private final Handler mAnimationThreadHandler = AnimationThread.getHandler();
// 获取android.anim.lf线程的Handler
private final Handler mSurfaceAnimationHandler = SurfaceAnimationThread.getHandler();
// 创建AnimationHandler
private final AnimationHandler mAnimationHandler;
/**
* There should only ever be one instance of this class. Usual spot for it is with
* @link WindowManagerService
*/
SurfaceAnimationRunner(Supplier<Transaction> transactionFactory,
PowerManagerInternal powerManagerInternal)
this(null /* callbackProvider */, null /* animatorFactory */,
transactionFactory.get(), powerManagerInternal);
@VisibleForTesting
SurfaceAnimationRunner(@Nullable AnimationFrameCallbackProvider callbackProvider,
AnimatorFactory animatorFactory, Transaction frameTransaction,
PowerManagerInternal powerManagerInternal)
// 在android.anim.lf线程获取Choreographer
mSurfaceAnimationHandler.runWithScissors(() -> mChoreographer = getSfInstance(),
0 /* timeout */);
mFrameTransaction = frameTransaction;
mAnimationHandler = new AnimationHandler();
mAnimationHandler.setProvider(callbackProvider != null
? callbackProvider
: new SfVsyncFrameCallbackProvider(mChoreographer));
mAnimatorFactory = animatorFactory != null
? animatorFactory
: SfValueAnimator::new;
mPowerManagerInternal = powerManagerInternal;
SurfaceAnimationRunner
主要创建SurfaceAnimationThread
和AnimationHandler
;
1.2.3.1 SurfaceAnimationThread的创建
[-> SurfaceAnimationThread.java]
/**
* Thread for running @link SurfaceAnimationRunner that does not hold the window manager lock.
*/
public final class SurfaceAnimationThread extends ServiceThread
private static SurfaceAnimationThread sInstance;
private static Handler sHandler;
private SurfaceAnimationThread()
super("android.anim.lf", THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
private static void ensureThreadLocked()
// 单例模式创建SurfaceAnimationThread
if (sInstance == null)
sInstance = new SurfaceAnimationThread();
sInstance.start();
sInstance.getLooper().setTraceTag(Trace.TRACE_TAG_WINDOW_MANAGER);
sHandler = new Handler(sInstance.getLooper());
public static Handler getHandler()
synchronized (SurfaceAnimationThread.class)
ensureThreadLocked();
return sHandler;
创建android.anim.lf
线程,并对外提供其绑定的Handler
;
1.3 WindowManagerService的初始化
[-> WindowMangerService.java]
/**
* Called after all entities (such as the @link ActivityManagerService) have been set up and
* associated with the @link WindowManagerService.
*/
public void onInitReady()
// 初始化策略类
initPolicy();
// Add ourself to the Watchdog monitors.
// WindowManagerService也实现了WatchDog.monitor接口
Watchdog.getInstance().addMonitor(this);
// 创建窗口水印处理类WaterMark
createWatermark();
1.3.1 PhoneWindowManager的初始化
private void initPolicy()
UiThread.getHandler().runWithScissors(new Runnable()
@Override
public void run()
// WindowManagerPolicy用于静态存储WindowManagerService所在的线程和Looper
WindowManagerPolicyThread.set(Thread.currentThread(), Looper.myLooper());
// PhoneWindowManager初始化[见1.3.1.1小节]
mPolicy.init(mContext, WindowManagerService.this, WindowManagerService.this);
, 0);
[-> PhoneWindowManager.java]
/** @inheritDoc */
@Override
public void init(Context context, IWindowManager windowManager,
WindowManagerFuncs windowManagerFuncs)
mContext = context;
mWindowManager = windowManager;
mWindowManagerFuncs = windowManagerFuncs;
mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
mActivityTaskManagerInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
mDreamManagerInternal = LocalServices.getService(DreamManagerInternal.class);
mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
mHandler = new PolicyHandler();
// 监听SettingsProvider
mSettingsObserver = new SettingsObserver(mHandler);
mSettingsObserver.observe();
// 快捷方式管理类
mShortcutManager = new ShortcutManager(context);
// 桌面Intent
mHomeIntent = new Intent(Intent.ACTION_MAIN, null);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
// register for multiuser-relevant broadcasts
// 注册用户切换的广播
filter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
context.registerReceiver(mMultiuserReceiver, filter);
// Controls rotation and the like.
// 初始化hdmi相关的状态
initializeHdmiState();
// 监听AppTransition相关的变化做锁屏相关的处理
mWindowManagerInternal.registerAppTransitionListener(new AppTransitionListener()
@Override
public int onAppTransitionStartingLocked(int transit, long duration,
long statusBarAnimationStartTime, long statusBarAnimationDuration)
return handleStartTransitionForKeyguardLw(transit, duration);
@Override
public void onAppTransitionCancelledLocked(int transit)
handleStartTransitionForKeyguardLw(transit, 0 /* duration */);
);
PhoneWindowManager
初始化时主要会读取系统配置,监听用户配置,监听系统广播等;
1.3.2 WatchDog监测
// Called by the heartbeat to ensure locks are not held indefnitely (for deadlock detection).
@Override
public void monitor()
synchronized (mGlobalLock)
检测mGlobalLock
是否死锁;
1.4 Display配置更新
[-> WindowManagerService.java]
public void displayReady()
synchronized (mGlobalLock)
if (mMaxUiWidth > 0)
mRoot.forAllDisplays(displayContent -> displayContent.setMaxUiWidth(mMaxUiWidth));
applyForcedPropertiesForDefaultDisplay();
mAnimator.ready();
mDisplayReady = true;
// Reconfigure all displays to make sure that forced properties and
// DisplayWindowSettings are applied.
mRoot.forAllDisplays(DisplayContent::reconfigureDisplayLocked);
mIsTouchDevice = mContext.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_TOUCHSCREEN);
try
mActivityTaskManager.updateConfiguration(null);
catch (RemoteException e)
1.5 PHASE_SYSTEM_SERVICES_READY阶段
[-> WindowManagerService.java]
public void systemReady()
mSystemReady = true;
mPolicy.systemReady();
mRoot.forAllDisplayPolicies(DisplayPolicy::systemReady);
mTaskSnapshotController.systemReady();
mHasWideColorGamutSupport = queryWideColorGamutSupport();
mHasHdrSupport = queryHdrSupport();
UiThread.getHandler().post(mSettingsObserver::loadSettings);
IVrManager vrManager = IVrManager.Stub.asInterface(
ServiceManager.getService(Context.VR_SERVICE));
if (vrManager != null)
try
final boolean vrModeEnabled = vrManager.getVrModeState();
synchronized (mGlobalLock)
vrManager.registerListener(mVrStateCallbacks);
if (vrModeEnabled)
mVrModeEnabled = vrModeEnabled;
mVrStateCallbacks.onVrStateChanged(vrModeEnabled);
catch (RemoteException e)
// Ignore, we cannot do anything if we failed to register VR mode listener
以上是关于Android 11.0源码系列之WMSWindowManagerService的主要内容,如果未能解决你的问题,请参考以下文章
Android 11.0源码系列之IMSInputManagerService
Android 11.0源码系列之IMSInputManager
Android 11.0源码系列之IMSInputDispatcher