前言
客户端开发中并不是直接和 WindowManagerService 交互,而是直接和本地对象 WindowManager 交互,然后由 WindowManager 完成和 WindowManagerService 的交互;
对于 Android 应用来说这个交互是透明的,应用感觉不到 WindowManagerService 的存在;
我们来介绍分析下窗口管理服务 WindowManagerService 的启动过程;
一、WindowManagerService的相关类
1、WindowManagerService概念
Framework层的窗口管理服务,职责是管理Android系统中所有window;窗口管理服务,继承IWindowManager.Stub,Binder服务端,因此WM与WMS的交互也是一个IPC过程。WMS主要做的事情如下:
2、WindowManager
应用与窗口管理服务WindowManagerService交互的接口
3、PhoneWindowManager
实现了窗口的各种策略,定义了窗口相关策略;
4、Choreographer
用户控制窗口动画、屏幕选择等操作,它拥有从显示子系统获取Vsync同步事件的能力,从而可以在合适的时机通知渲染动作,避免在渲染的过程中因为发生屏幕重绘而导致的画面撕裂。WMS使用Choreographer负责驱动所有的窗口动画、屏幕旋转动画、墙纸动画的渲染;
5、DisplayContent
6、WindowState
描述窗口的状态信息以及和WindowManagerService进行通信,一般一个窗口对应一个WindowState。它用来表示一个窗口的所有属性;
7、WindowToken
8、Session
App进程通过建立Session代理对象和Session对象通信,进而和WMS建立连接;
9、SurfaceFlinger
SurfaceFlinger负责管理Android系统的帧缓冲区(Frame Buffer),Android设备的显示屏被抽象为一个帧缓冲区,而Android系统中的SurfaceFlinger服务就是通过向这个帧缓冲区写入内容来绘制应用程序中的用户界面的;
10、InputManager
IMS实例。管理每个窗口的输入事件通道(InputChannel)以及向通道上派发事件
11、Animator
所有窗口动画的总管(WindowStateAnimator对象)。在Choreographer的驱动下,逐个渲染所有的动画
二、WMS启动流程
WMS的启动,依然是由SystemServer进行启动,在SystemServer的main函数中调用startOtherServices方法创建WMS;
1、SystemServer#startOtherServices
private void startOtherServices() {
...
try {
...
// 创建WMS对象
// 创建WMS对象需要依赖于InputManager、PhoneWindowManager、和AMS
// IMS是用来管理每个窗口的输入事件通道以及向通道上派发事件
// PhoneWindowManager是实现了窗口的各种策略,定义了窗口相关策略
// 比如:告诉WMS某一个类型Window的Z-Order的值是多少,帮助WMS矫正不合理的窗口属性,
// 为WMS监听屏幕旋转的状态,预处理一些系统按键事件(例如HOME、BACK键等的默认行为就是在这里实现的)等
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
traceEnd();
traceBeginAndSlog("SetWindowManagerService");
// 将AMS与WMS做绑定
mActivityManagerService.setWindowManager(wm);
traceEnd();
traceBeginAndSlog("WindowManagerServiceOnInitReady");
// 这里主要是调用initPolicy用来初始化PhoneWindowManager
wm.onInitReady();
traceEnd();
...
}
...
traceBeginAndSlog("MakeDisplayReady");
try {
// 主要是初始化UI尺寸
wm.displayReady();
} catch (Throwable e) {
reportWtf("making display ready", e);
}
traceEnd();
...
traceBeginAndSlog("MakeWindowManagerServiceReady");
try {
// 准备工作已经完成
wm.systemReady();
} catch (Throwable e) {
reportWtf("making Window Manager Service ready", e);
}
traceEnd();
...
}
2、WindowManagerService#main
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);
}
@VisibleForTesting
public static WindowManagerService main(final Context context, final InputManagerService im,
final boolean showBootMsgs, final boolean onlyCore, WindowManagerPolicy policy,
ActivityTaskManagerService atm, TransactionFactory transactionFactory) {
// wms是运行在android.display线程
DisplayThread.getHandler().runWithScissors(() ->
sInstance = new WindowManagerService(context, im, showBootMsgs, onlyCore, policy,
atm, transactionFactory), 0);
return sInstance;
}
3、Handler#runWithScissors
上面的runWithScissors传入的就是一个Runnable实例,只不过是采用了lambda表达式的做法,所以Runnable的run()方法的方法体是就是:
sInstance = new WindowManagerService(context, im, showBootMsgs, onlyCore, policy,
atm, transactionFactory), 0);
public final boolean runWithScissors(@NonNull Runnable r, long timeout) {
if (r == null) {
throw new IllegalArgumentException("runnable must not be null");
}
if (timeout < 0) {
throw new IllegalArgumentException("timeout must be non-negative");
}
// 如果调用runWithScissors方法的线程是与消息处理线程在同一个线程
// 则直接执行Runnable的run方法。
if (Looper.myLooper() == mLooper) {
r.run();
return true;
}
// 如果调用runWithScissors方法的线程与消息处理线程不是同一个,则创建一个BlockingRunnable
BlockingRunnable br = new BlockingRunnable(r);
return br.postAndWait(this, timeout);
}
4、BlockingRunnable方法介绍
private static final class BlockingRunnable implements Runnable {
private final Runnable mTask;
private boolean mDone;
public BlockingRunnable(Runnable task) {
mTask = task;
}
@Override
public void run() {
try {
mTask.run();
} finally {
synchronized (this) {
mDone = true;
notifyAll();
}
}
}
public boolean postAndWait(Handler handler, long timeout) {
// 调用postAndWait的时候,先调用handler对象的post将消息发送出
// 如果入队成功,则为true,则开始阻塞
if (!handler.post(this)) {
return false;
}
// 在上面的方法调用中,timeout=0,则阻塞。
synchronized (this) {
if (timeout > 0) {
final long expirationTime = SystemClock.uptimeMillis() + timeout;
// 如果mDone为false的时候,则会等待,只有为true的时候,会执行
while (!mDone) {
long delay = expirationTime - SystemClock.uptimeMillis();
if (delay <= 0) {
return false; // timeout
}
try {
wait(delay);
} catch (InterruptedException ex) {
}
}
} else {
while (!mDone) {
try {
wait();
} catch (InterruptedException ex) {
}
}
}
}
return true;
}
}
5、WindowManagerService构造器
private WindowManagerService(Context context, InputManagerService inputManager,
boolean showBootMsgs, boolean onlyCore, WindowManagerPolicy policy,
ActivityTaskManagerService atm, TransactionFactory transactionFactory) {
installLock(this, INDEX_WINDOW);
mGlobalLock = atm.getGlobalLock();
mAtmService = atm;
mContext = context;
mAllowBootMessages = showBootMsgs;
mOnlyCore = onlyCore;
// 各种变量读取
mLimitedAlphaCompositing = context.getResources().getBoolean(
com.android.internal.R.bool.config_sf_limitedAlpha);
mHasPermanentDpad = context.getResources().getBoolean(
com.android.internal.R.bool.config_hasPermanentDpad);
mInTouchMode = context.getResources().getBoolean(
com.android.internal.R.bool.config_defaultInTouchMode);
......
mInputManager = inputManager;
mDisplayManagerInternal =
LocalServices.getService(DisplayManagerInternal.class);
// Display设置
mDisplayWindowSettings = new DisplayWindowSettings(this);
mTransactionFactory = transactionFactory;
mTransaction = mTransactionFactory.make();
//PhoneWindowManager(继承于WindowManagerPolicy, 用来提供UI相关的一些行为)
mPolicy = policy;
// 在一个单独的task中执行动画和Surface操作的类
mAnimator = new WindowAnimator(this);
// 根Window容器
mRoot = new RootWindowContainer(this);
// 用来确定Window和Surface的位置
mWindowPlacerLocked = new WindowSurfacePlacer(this);
// 任务快照管理器(当App不可见时, 会将Task的快照以Bitmap形式存在缓存中)
mTaskSnapshotController = new TaskSnapshotController(this);
LocalServices.addService(WindowManagerPolicy.class, mPolicy);
mDisplayManager =
(DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
// Keyguard处理器
mKeyguardDisableHandler =
KeyguardDisableHandler.create(mContext, mPolicy, mH);
// PowerManager是控制设备电池状态的管理器
mPowerManager =
(PowerManager)context.getSystemService(Context.POWER_SERVICE);
// PowerManagerInternal是PowerMananger的本地服务
mPowerManagerInternal =
LocalServices.getService(PowerManagerInternal.class);
if (mPowerManagerInternal != null) {
mPowerManagerInternal.registerLowPowerModeObserver(
new PowerManagerInternal.LowPowerModeListener() {
@Override
public int getServiceType() {
return ServiceType.ANIMATION;
}
@Override
public void onLowPowerModeChanged(PowerSaveState result) {
synchronized (mGlobalLock) {
// 低电量模式发生变化时, 需要调整对应的动画
final boolean enabled = result.batterySaverEnabled;
if (mAnimationsDisabled != enabled && !mAllowAnimationsInLowPowerMode) {
mAnimationsDisabled = enabled;
dispatchNewAnimatorScaleLocked(null);
}
}
}
});
// 获取是否允许动画
mAnimationsDisabled =
mPowerManagerInternal.getLowPowerState(
ServiceType.ANIMATION).batterySaverEnabled;
}
mScreenFrozenLock =
mPowerManager.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "SCREEN_FROZEN");
mScreenFrozenLock.setReferenceCounted(false);
// 获取IActivity.Stub.Proxy(new BinderProxy())
mActivityManager = ActivityManager.getService();
// 获取IActivityTaskManager.Stub.Proxy
mActivityTaskManager = ActivityTaskManager.getService();
// ActivityManagerInternal是ActivityManager的本地服务
mAmInternal =
LocalServices.getService(ActivityManagerInternal.class);
// ActivityTaskManagerInternal是ActivityTaskManager的本地服务
mAtmInternal =
LocalServices.getService(ActivityTaskManagerInternal.class);
mAppOps =
(AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
AppOpsManager.OnOpChangedInternalListener opListener =
new AppOpsManager.OnOpChangedInternalListener() {
@Override
public void onOpChanged(int op, String packageName) {
updateAppOpsState();
}
};
mAppOps.startWatchingMode(OP_SYSTEM_ALERT_WINDOW, null, opListener);
mAppOps.startWatchingMode(AppOpsManager.OP_TOAST_WINDOW,
null, opListener);
// PackageManagerInternal是PackageManager的本地服务
mPmInternal = LocalServices.getService(PackageManagerInternal.class);
// 注册Package suspend/unsuspend广播
final IntentFilter suspendPackagesFilter = new IntentFilter();
suspendPackagesFilter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
suspendPackagesFilter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
context.registerReceiverAsUser(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String[] affectedPackages =
intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
final boolean suspended =
Intent.ACTION_PACKAGES_SUSPENDED.equals(intent.getAction());
updateHiddenWhileSuspendedState(
new ArraySet<>(Arrays.asList(affectedPackages)), suspended);
}
}, UserHandle.ALL, suspendPackagesFilter, null, null);
// 获取并设置window scale设置
final ContentResolver resolver = context.getContentResolver();
mWindowAnimationScaleSetting = Settings.Global.getFloat(resolver,
Settings.Global.WINDOW_ANIMATION_SCALE, mWindowAnimationScaleSetting);
......
// 注册广播, 当DevicePolicyManager状态发生变化时设置keyguard属性是否可用
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
mContext.registerReceiverAsUser(mBroadcastReceiver,
UserHandle.ALL, filter, null, null);
mLatencyTracker = LatencyTracker.getInstance(context);
mSettingsObserver = new SettingsObserver();
......
mSurfaceAnimationRunner = new SurfaceAnimationRunner(mPowerManagerInternal);
mAllowTheaterModeWakeFromLayout = context.getResources().getBoolean(
com.android.internal.R.bool.config_allowTheaterModeWakeFromWindowLayout);
// Task定位控制器
mTaskPositioningController = new TaskPositioningController(this,
mInputManager, mActivityTaskManager, mH.getLooper());
// View的拖/拉操作控制器
mDragDropController = new DragDropController(this, mH.getLooper());
......
// 注册WindowManager的本地服务WindowManagerInternal
LocalServices.addService(WindowManagerInternal.class, new LocalService());
}
6、onInitReady
public void onInitReady() {
// 初始化PhoneWindowManager
initPolicy();
// 添加Watchdog monitor
Watchdog.getInstance().addMonitor(this);
// 调用SurfaceControl.openTransaction(), 启动一个事务
openSurfaceTransaction();
// 创建水印
createWatermarkInTransaction();
// 结束事务
closeSurfaceTransaction("createWatermarkInTransaction");
// 显示模拟器显示层
showEmulatorDisplayOverlayIfNeeded();
}
7、 initPolicy
private void initPolicy() {
UiThread.getHandler().runWithScissors(new Runnable() {
@Override
public void run() {
WindowManagerPolicyThread.set(Thread.currentThread(),
Looper.myLooper());
mPolicy.init(mContext, WindowManagerService.this,
WindowManagerService.this);
}
}, 0);
}
PhoneWindowManager 的初始化运行在 “android.ui” 线程;
8、 displayReady
public void displayReady() {
synchronized (mGlobalLock) {
// 设置RootWindowContainer的Window列表的最大宽度
if (mMaxUiWidth > 0) {
mRoot.forAllDisplays(
displayContent -> displayContent.setMaxUiWidth(mMaxUiWidth));
}
final boolean changed = applyForcedPropertiesForDefaultDisplay();
mAnimator.ready();
mDisplayReady = true;
if (changed) {
// 重新配置DiaplayContent属性
reconfigureDisplayLocked(getDefaultDisplayContentLocked());
}
mIsTouchDevice = mContext.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_TOUCHSCREEN);
}
// 1.修改当前configuration 2.确保当前Activity正在运行当前configuration
mActivityTaskManager.updateConfiguration(null);
// 更新CircularDisplayMask
updateCircularDisplayMaskIfNeeded();
}
9、systemReady
public void systemReady() {
mSystemReady = true;
mPolicy.systemReady();
mRoot.forAllDisplayPolicies(DisplayPolicy::systemReady);
mTaskSnapshotController.systemReady();
// 是否支持色域
mHasWideColorGamutSupport = queryWideColorGamutSupport();
// 是否支持HDR渲染
mHasHdrSupport = queryHdrSupport();
UiThread.getHandler().post(mSettingsObserver::updateSystemUiSettings);
UiThread.getHandler().post(mSettingsObserver::updatePointerLocation);
// 获取IVrManager.Stub.Proxy, 并注册状态变化listener
IVrManager vrManager = IVrManager.Stub.asInterface(
ServiceManager.getService(Context.VR_SERVICE));
if (vrManager != null) {
final boolean vrModeEnabled = vrManager.getVrModeState();
synchronized (mGlobalLock) {
vrManager.registerListener(mVrStateCallbacks);
if (vrModeEnabled) {
mVrModeEnabled = vrModeEnabled;
mVrStateCallbacks.onVrStateChanged(vrModeEnabled);
}
}
}
}
总结
快年底了,一起加油努力
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8