看了罗老师的的博客很久了,特别羡慕,写的非常认真而且详细,所以呢,也经常向大家推荐,各位卓友如果有时间,请多看一下,对自己从整体上掌握Android Framework架构非常有益。自己的学习在同时,也跟着源码分析,得出自己的结论,只是单纯的看罗老师的博客,看完还是一头雾水,只有自己完整完整走一遍,才会有一定的掌握。
Android当中的GUI绘图应该算是最重要的一块了,因为所有的应用都最直接和用户接触,当然这块也是特别复杂的。自己看了好久,才有一点脉络,记下来,怕以后忘掉了。
从罗老师的博客当中,可以了解到,Application都会与SurfaceFlinger连接,并得到一个匿名的binder对象,以便能够绘制自己的UI,并在绘制完成后,请求SurfaceFlinger对自己的UI数据进行渲染。一个Application在SurfaceFlinger端对应有一个Client的对象,对应的代码如下:
sp
SurfaceFlinger::createConnection()
{
sp
bclient;
sp
client(new Client(this));
status_t err = client->initCheck();
if (err == NO_ERROR) {
bclient = client;
}
return bclient;
}
到这里,Application就取得与SurfaceFlinger的正常连接了,好了,那我们的目标现在就非常清晰了,Application是怎么执行到这里的呢?我们还是从ViewRootImpl类来看起,Application中的每个界面对应一个Activity,而每个Activity都对应一个Window、一个ViewRootImpl、一个WindowState、一个Surface,这些如果有疑问的,可以去看罗老师的博客。ViewRootImpl的创建是在WindowManagerGlobal当中的,代码如下:
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
if (display == null) {
throw new IllegalArgumentException("display must not be null");
}
if (!(params instanceof WindowManager.LayoutParams)) {
throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
}
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
if (parentWindow != null) {
parentWindow.adjustLayoutParamsForSubWindow(wparams);
} else {
// If there's no parent, then hardware acceleration for this view is
// set from the application's hardware acceleration setting.
final Context context = view.getContext();
if (context != null
&& (context.getApplicationInfo().flags
& ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
}
}
ViewRootImpl root;
View panelParentView = null;
synchronized (mLock) {
// Start watching for system property changes.
if (mSystemPropertyUpdater == null) {
mSystemPropertyUpdater = new Runnable() {
@Override public void run() {
synchronized (mLock) {
for (int i = mRoots.size() - 1; i >= 0; --i) {
mRoots.get(i).loadSystemProperties();
}
}
}
};
SystemProperties.addChangeCallback(mSystemPropertyUpdater);
}
int index = findViewLocked(view, false);
if (index >= 0) {
if (mDyingViews.contains(view)) {
// Don't wait for MSG_DIE to make it's way through root's queue.
mRoots.get(index).doDie();
} else {
throw new IllegalStateException("View " + view
+ " has already been added to the window manager.");
}
// The previous removeView() had not completed executing. Now it has.
}
// If this is a panel window, then find the window it is being
// attached to for future reference.
if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
final int count = mViews.size();
for (int i = 0; i < count; i++) {
if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
panelParentView = mViews.get(i);
}
}
}
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
}
// do this last because it fires off messages to start doing things
try {
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
// BadTokenException or InvalidDisplayException, clean up.
synchronized (mLock) {
final int index = findViewLocked(view, false);
if (index >= 0) {
removeViewLocked(index, true);
}
}
throw e;
}
}
public ViewRootImpl(Context context, Display display) {
mContext = context;
mWindowSession = WindowManagerGlobal.getWindowSession();
mDisplay = display;
mBasePackageName = context.getBasePackageName();
mDisplayAdjustments = display.getDisplayAdjustments();
mThread = Thread.currentThread();
mLocation = new WindowLeaked(null);
mLocation.fillInStackTrace();
mWidth = -1;
mHeight = -1;
mDirty = new Rect();
mTempRect = new Rect();
mVisRect = new Rect();
mWinFrame = new Rect();
mWindow = new W(this);
mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
mViewVisibility = View.GONE;
mTransparentRegion = new Region();
mPreviousTransparentRegion = new Region();
// [+LEUI-9331]
mPreBlurParams = new BlurParams();
// [-LEUI-9331]
mFirst = true; // true for the first time the view is added
mAdded = false;
mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
mAccessibilityManager = AccessibilityManager.getInstance(context);
mAccessibilityInteractionConnectionManager =
new AccessibilityInteractionConnectionManager();
mAccessibilityManager.addAccessibilityStateChangeListener(
mAccessibilityInteractionConnectionManager);
mHighContrastTextManager = new HighContrastTextManager();
mAccessibilityManager.addHighTextContrastStateChangeListener(
mHighContrastTextManager);
mViewConfiguration = ViewConfiguration.get(context);
mDensity = context.getResources().getDisplayMetrics().densityDpi;
mNoncompatDensity = context.getResources().getDisplayMetrics().noncompatDensityDpi;
mFallbackEventHandler = new PhoneFallbackEventHandler(context);
mChoreographer = Choreographer.getInstance();
mDisplayManager = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);
loadSystemProperties();
/**
* M: increase instance count and check log property to determine
* whether to enable/disable log system. @{
*/
mIdent = sIdent++;
checkViewRootImplLogProperty();
if (LOCAL_LOGV) {
enableLog(true, "a");
}
if (DEBUG_LIFECYCLE) {
Log.v(TAG, "ViewRootImpl construct: context = " + context + ", mThread = " + mThread
+ ", mChoreographer = " + mChoreographer + ", mTraversalRunnable = "
+ mTraversalRunnable + ", this = " + this);
}
}
public static IWindowSession getWindowSession() {
synchronized (WindowManagerGlobal.class) {
if (sWindowSession == null) {
try {
InputMethodManager imm = InputMethodManager.getInstance();
IWindowManager windowManager = getWindowManagerService();
sWindowSession = windowManager.openSession(
new IWindowSessionCallback.Stub() {
@Override
public void onAnimatorScaleChanged(float scale) {
ValueAnimator.setDurationScale(scale);
}
},
imm.getClient(), imm.getInputContext());
} catch (RemoteException e) {
Log.e(TAG, "Failed to open window session", e);
}
}
return sWindowSession;
}
}
private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
boolean insetsPending) throws RemoteException {
float appScale = mAttachInfo.mApplicationScale;
boolean restore = false;
if (params != null && mTranslator != null) {
restore = true;
params.backup();
mTranslator.translateWindowLayout(params);
}
if (params != null) {
if (DBG) Log.d(TAG, "WindowLayout in layoutWindow:" + params);
}
mPendingConfiguration.seq = 0;
if (DEBUG_LAYOUT) {
Log.d(TAG, ">>>>>> CALLING relayoutW+ " + mWindow + ", params = " + params
+ ",viewVisibility = " + viewVisibility + ", insetsPending = " + insetsPending
+ ", appScale = " + appScale + ", mWinFrame = " + mWinFrame + ", mSeq = "
+ mSeq + ", mPendingOverscanInsets = " + mPendingOverscanInsets
+ ", mPendingContentInsets = " + mPendingContentInsets
+ ", mPendingVisibleInsets = " + mPendingVisibleInsets
+ ", mPendingStableInsets = " + mPendingStableInsets
+ ", mPendingOutsets = " + mPendingOutsets
+ ", mPendingConfiguration = " + mPendingConfiguration + ", mSurface = "
+ mSurface + ",valid = " + mSurface.isValid() + ", mOrigWindowType = "
+ mOrigWindowType + ",this = " + this);
}
if (params != null && mOrigWindowType != params.type) {
// For compatibility with old apps, don't crash here.
if (mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Slog.w(TAG, "Window type can not be changed after "
+ "the window is added; ignoring change of " + mView);
params.type = mOrigWindowType;
}
}
int relayoutResult = mWindowSession.relayout(
mWindow, mSeq, params,
(int) (mView.getMeasuredWidth() * appScale + 0.5f),
(int) (mView.getMeasuredHeight() * appScale + 0.5f),
viewVisibility, insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0,
mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
mPendingStableInsets, mPendingOutsets, mPendingConfiguration, mSurface);
if (DEBUG_LAYOUT) {
Log.d(TAG, "<<<<<< BACK FROM relayoutW- : res = " + relayoutResult + ", mWinFrame = "
+ mWinFrame + ", mPendingOverscanInsets = " + mPendingOverscanInsets
+ ", mPendingContentInsets = " + mPendingContentInsets
+ ", mPendingVisibleInsets = " + mPendingVisibleInsets
+ ", mPendingStableInsets = " + mPendingStableInsets
+ ", mPendingOutsets = " + mPendingOutsets
+ ", mPendingConfiguration = " + mPendingConfiguration + ", mSurface = "
+ mSurface + ",valid = " + mSurface.isValid() + ",params = " + params
+ ", this = " + this);
}
if (restore) {
params.restore();
}
if (mTranslator != null) {
mTranslator.translateRectInScreenToAppWinFrame(mWinFrame);
mTranslator.translateRectInScreenToAppWindow(mPendingOverscanInsets);
mTranslator.translateRectInScreenToAppWindow(mPendingContentInsets);
mTranslator.translateRectInScreenToAppWindow(mPendingVisibleInsets);
mTranslator.translateRectInScreenToAppWindow(mPendingStableInsets);
}
return relayoutResult;
}
void attach() {
if (WindowManagerService.localLOGV) Slog.v(
TAG, "Attaching " + this + " token=" + mToken
+ ", list=" + mToken.windows);
mSession.windowAddedLocked();
}
static jlong nativeCreate(JNIEnv* env, jclass clazz) {
SurfaceComposerClient* client = new SurfaceComposerClient();
client->incStrong((void*)nativeCreate);
return reinterpret_cast
(client);
}