代码实现添加悬浮窗
mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
mWindowView = LayoutInflater.from(getApplication()).inflate(R.layout.layout_window, null);
mWindowManager.addView(mWindowView, wmParams);
分析的源码为:android 8.0 api26
关键代码:WindowManager.addView()
源码位置:android.view.WindowManagerImpl#addView
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}
关键代码:mGlobal.addView()
源码位置:android.view.WindowManagerGlobal#addView
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
// 参数效验
...
ViewRootImpl root;
synchronized (mLock) {
// 查找缓存,类型效验
...
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
}
try {
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
// who care?
}
}
关键代码:root.setView(...)
源码位置:android.view.ViewRootImpl#setView
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
// 各种属性读取,赋值及效验
...
mView = view;
mWindowAttributes.copyFrom(attrs);
...
mAttachInfo.mRootView = view;
try {
...
//1-进行View绘制三大流程;
requestLayout();
...
int res; /* = WindowManagerImpl.ADD_OKAY; */
//2-会通过WindowSession完成Window的添加过程(一次IPC调用)
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttri