百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Android Framework核心:Window窗口概念

nanshan 2024-11-20 19:25 8 浏览 0 评论

Window

public abstract class Window

Window 是一个抽象基类,用于显示内容以及用户与应用程序的交互。实际上,Window是一个透明的矩形,我们所有的 View 都绘制在上面。

当一个Activity被创建时,ActivityThread类会调用该Activity的 attach()方法。attach()方法在onCreate()之前调用。在attach()方法中,会给Activity创建一个Window:

@UnsupportedAppUsage
final void attach(Context context, ... ) {
  // ...
  mWindow = new PhoneWindow(this, window, activityConfigCallback);
  // ...
}

PhoneWindow就是Window的具体实现,它有2个重要属性 private DecorView mDecor 和 ViewGroup mContentParent。

DecorView 是 Activity 的视图层次结构中的根容器。 DecorView 扩展了 FrameLayout。

窗口具有单个视图层次结构,这些视图附加到窗口并提供该窗口的行为。

另外还需要注意的是,DecorView 的布局是根据为 Activity 或整个应用程序指定的主题创建的。

// PhoneWindow.java
// ...
mContentParent = generateLayout(mDecor);
// ...
protected ViewGroup generateLayout(DecorView decor){
  // ...
  int layoutResource;
  int features = getLocalFeatures();
  // System.out.println("Features: 0x" + Integer.toHexString(features));
  if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
    layoutResource = R.layout.screen_swipe_dismiss;
    setCloseOnSwipeEnabled(true);
  } else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
    if (mIsFloating) {
      TypedValue res = new TypedValue();
      getContext().getTheme().resolveAttribute(R.attr.dialogTitleIconsDecorLayout, res, true);
      layoutResource = res.resourceId;
    } else {
    	layoutResource = R.layout.screen_title_icons;
    }
    // XXX Remove this once action bar supports these features.
    removeFeature(FEATURE_ACTION_BAR);
    // System.out.println("Title Icons!");
  } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0  && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
    // Special case for a window with only a progress bar (and title).
    // XXX Need to have a no-title version of embedded windows. 
    layoutResource = R.layout.screen_progress;
    // System.out.println("Progress!");
  } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
    // Special case for a window with a custom title.
    // If the window is floating, we need a dialog layout 
    if (mIsFloating) {
      TypedValue res = new TypedValue();
      getContext().getTheme().resolveAttribute(R.attr.dialogCustomTitleDecorLayout, res, true);
      layoutResource = res.resourceId;
    } else {
      layoutResource = R.layout.screen_custom_title;
    }
    // XXX Remove this once action bar supports these features.
    removeFeature(FEATURE_ACTION_BAR);
  } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
    // If no other features and not embedded, only need a title.
    // If the window is floating, we need a dialog layout 
    if (mIsFloating) {
      TypedValue res = new TypedValue();
      getContext().getTheme().resolveAttribute(R.attr.dialogTitleDecorLayout, res, true);
      layoutResource = res.resourceId;
    } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
      layoutResource = a.getResourceId(  R.styleable.Window_windowActionBarFullscreenDecorLayout,  R.layout.screen_action_bar);
    } else {
      layoutResource = R.layout.screen_title;
    }
    // System.out.println("Title!");
  } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
  	layoutResource = R.layout.screen_simple_overlay_action_mode;
  } else {
    // Embedded, so no decoration is needed.
    layoutResource = R.layout.screen_simple;
    // System.out.println("Simple!");
  }
  // ...
}
// **Activity.java
// ...
final View root = inflater.inflate(layoutResource, null);

从上边的结构可以看出,除了 Activity 的内容,还需要存储其他的 view,所以有了另外个属性 mContentParent。mContentParent 是一个 ViewGroup,旨在将其他 View 元素保存在其内部,也就是我们添加到 Activity 的 UI 元素的根容器。

此外,还有两个方法 setContentView() 和 addContentView()。

setContentView() 方法作用大家应该都知道,就不具体说了。它有三个重载方法 setContentView(int layoutResID)、setContentView(View view)、setContentView(View view, ViewGroup.LayoutParams params),可以根据具体需要选择合适的。

addContentView()和 setContentView()的作用差不多,差别在于前者不会删除已添加到 mContentParent 的元素,而是将 View 添加为子元素。

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  TextView textView = new TextView(this);
  textView.setText("Hello Alex");
  textView.setTextSize(50);
  ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
  addContentView(textView, lp);
}

查看结果如下:

Surface

Activity、Dialog、StatusBar 等等元素都有自己的 Window,而每个 Window 都有自己的Surface 进行渲染。

Surface 是 SurfaceFlinger 服务共享的缓冲区列表的简单封装。

SurfaceFlinger 是一个 Android 系统服务,负责将所有 Surface 应用程序和系统布置到单个缓冲区中,最终应由显示控制器呈现。SurfaceFlinger 不能直接提供给应用程序开发人员。

一个常见的误解是 SurfaceFinger 是用于绘图的,但事实并非如此。绘图是 OpenGL 的工作。 SurfaceFlinger 使用 OpenGL 进行图像合成。

合成的结果将被放置在系统缓冲区,而这个缓冲区就是显示控制器检索数据的源。显示控制器检索到数据后展现到屏幕上,这样子我们才能在屏幕上看到图像。

Surface 通常有多个缓冲区(通常是两个)来执行双缓冲渲染:应用程序可以渲染其下一个 UI 状态,而 SurfaceFlinger 使用最后一个缓冲区值组合屏幕,而无需等待渲染完成。

简单来说,Surface 是一个包含在屏幕上组成的像素的对象。

每当一个窗口需要重绘时,下面的过程都会发生在该窗口的上:

Window 调用 Surface 上的 lockCanvas方法,lockCanvas 方法返回一个 Canvas 对象,然后将 Canvas 对象传递给 View 的 onDraw 方法。

等 Canvas 工作完成后,再调用 Surface 上的 unlockCanvasAndPost 方法,并将 Canvas 传递到缓冲区进行绘制。

Canvas 对象不绘制任何东西,它只是一组需要执行的命令。例如:

drawCircle(centerX, centerY, radius, paint)
drawRoundRect(left, top, right, bottom, cornerRadiusX, cornerRadiusY, paint)

lockCanvas(Rect inOutDirty) 和 unlockCanvasAndPost(Canvas canvas) 方法是同步的,同步保证同一时刻只有一个线程可以绘制。

ViewRootImpl

ViewRootImpl 是View层次结构的最顶层,它是一个特殊的View,不渲染任何东西,但负责Window 和 View 之间的交互。

ViewRootImpl 拥有 DecorView 实例,通过它控制 DecorView 的渲染。

具体后面会说到。

WindowManager

上边都是说一些 Window 的结构以及绘图机制,但这些结构(也就是DecorView)是怎么添加到屏幕上的?这里就用到了 WindowManager。

Activity 显示在屏幕上 回调的方法是 onResume(), 那顺着这个查代码就会发现 ActivityThread 中的 handleResumeActivity 方法:

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
  // .....
  if (r.window == null && !a.mFinished && willBeVisible) {
    r.window = r.activity.getWindow();
    View decor = r.window.getDecorView();
    decor.setVisibility(View.INVISIBLE);
    ViewManager wm = a.getWindowManager();
    WindowManager.LayoutParams l = r.window.getAttributes();
    a.mDecor = decor;
    l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
    l.softInputMode |= forwardBit;
    if (r.mPreserveWindow) {
      a.mWindowAdded = true;
      r.mPreserveWindow = false;
      // Normally the ViewRoot sets up callbacks with the Activity
      // in addView->ViewRootImpl#setView. If we are instead reusing // the decor view we have to notify the view root that the
      // callbacks may have changed. 
      ViewRootImpl impl = decor.getViewRootImpl();
      if (impl != null) {
      	impl.notifyChildRebuilt();
      }
    }
    if (a.mVisibleFromClient) {
      if (!a.mWindowAdded) {
        a.mWindowAdded = true;
        wm.addView(decor, l);
      } else {
        // The activity will get a callback for this {@link LayoutParams} change
        // earlier. However, at that time the decor will not be set (this is set // in this method), so no action will be taken. This call ensures the // callback occurs with the decor set. 
        a.onWindowAttributesChanged(l);
      }
    }

    // If the window has already been added, but during resume
    // we started another activity, then don't yet make the
    // window visible. } else if (!willBeVisible) {
    if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
    r.hideForNow = true;
  }

  // Get rid of anything left hanging around.
  cleanUpPendingRemoveWindows(r, false /* force */);

  // The window is now visible if it has been added, we are not
  // simply finishing, and we are not starting another activity.
  if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
    if (r.newConfig != null) {
      performConfigurationChangedForActivity(r, r.newConfig);
      if (DEBUG_CONFIGURATION) {
      	Slog.v(TAG, "Resuming activity " + r.activityInfo.name + " with newConfig " + r.activity.mCurrentConfig);
      }
      r.newConfig = null;
    }
    if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
    WindowManager.LayoutParams l = r.window.getAttributes();
    if ((l.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)  != forwardBit) {
    	l.softInputMode = (l.softInputMode & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))  | forwardBit;
      if (r.activity.mVisibleFromClient) {
        ViewManager wm = a.getWindowManager();
        View decor = r.window.getDecorView();
        wm.updateViewLayout(decor, l);
      }
    }

    r.activity.mVisibleFromServer = true;
    mNumVisibleActivities++;
    if (r.activity.mVisibleFromClient) {
    	r.activity.makeVisible();
    }
  }

  r.nextIdle = mNewActivities;
  mNewActivities = r;
  if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
  Looper.myQueue().addIdleHandler(new Idler());
}

这个方法主要做了如下的事情:

首先,获取 DecorView 并使其不可见,然后通过 wm.addView(decor, l) 将View添加到WindowManager 中。

然后,调用 makeVisible 方法使 View 可见。如果此时 WindowManager 中没有添加DecorView,则会添加。

// Activity.java
void makeVisible() {
  if (!mWindowAdded) {
    ViewManager wm = getWindowManager();
    wm.addView(mDecor, getWindow().getAttributes());
    mWindowAdded = true;
  }
  mDecor.setVisibility(View.VISIBLE);
}

WindowManager 接口由 WindowManagerImpl 实现,它通过 WindowManagerGlobal 代理实现 addView 方法 (这里涉及到 Android 的 Binder 机制)。我们看一下 addView 方法:

// WindowManagerImpl.java
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
  applyDefaultToken(params);
  mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}

WindowManagerGlobal 中创建了 ViewRootImpl :

// WindowManagerGlobal.java
public void addView(View view, ViewGroup.LayoutParams params,Display display, Window parentWindow) {
  // ....

  ViewRootImpl root;
  View panelParentView = null;

  synchronized (mLock) {
    // ....

    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.
      if (index >= 0) {
      	removeViewLocked(index, true);
      }
      throw e;
    }
  }
}

WindowManagerGlobal 存储 ViewRootImpl,并将 DecorView 添加到 ViewRootImpl 中。

总结

  1. 在 ActivityThread 中,调用 handleResumeActivity 方法,在该方法中我们获取了DecorView。我们将 DecorView 传递给 WindowManager,WindowManager 又调用 WindowManagerGlobal 来添加 DecorView。
  2. WindowManagerGlobal 创建一个 ViewRootImpl 并根据需要添加一个 DecorView。
  3. ViewRootImpl 是 DecorView 的父级,因为 DecorView 是我们布局的顶层。
  4. DecorView 是在 PhoneWindow 上创建的。调用链创建DecorView:Activity.setContentView -> PhoneWindow.setContentView -> installDecor

View

现在我们了解了应用程序中的视图层次结构,让我们讨论什么是视图。

视图是位于窗口上的交互式 UI 元素。

初始化视图流程如下:

构造函数(Constructor)

当我们创建视图时,会调用其中一个构造函数。 View 有四个构造函数。

// should be used if we are creating View from code
View(Context context)

// should be used if we are creating from XML
View(Context context, @Nullable AttributeSet attrs)

// The other two constructors are meant to be called by child classes
// to provide a default style via the theme attribute and
// direct default style resource.
View(Context context, @Nullable AttributeSet attrs, int defStyleAttr)
View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes)

核心方法

onAttachedToWindow

当视图附加到窗口时调用该方法。此时它就有了Surface,View可以开始绘制了。

请注意,保证在 onDraw(Canvas) 之前调用此函数,但可以在第一个 onDraw 之前的任何时间调用它,包括 onMeasure(int, int) 之前或之后。

当我们在 Activity 或 Fragment.onCreateView 上创建 Inflate View 时,会调用此方法。

onDetachedFromWindow

当视图与窗口分离时调用。此时Surface不可用,View无法绘制任何东西。

onMeasure

调用此方法来确定视图的尺寸。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),  getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

该方法以变量 widthMeasureSpec 和 heightMeasureSpec 作为参数,它们依次表示测量 View 的宽度和高度的要求。如果我们独立指定View的大小,那么我们应该使用 setMeasuredDimension 方法,在该方法中传递View的高度和宽度。

MeasureSpec 是 View 的一个内部类,是用于确定 Android 中视图尺寸的类。它封装了从父元素传递到子元素的布局要求。每个 MeasureSpec 代表宽度或高度的要求。 MeasureSpec 由大小和模式组成。可以采用三种模式:

  • UNSPECIFIED:View的大小可以是任意的,父View不会以任何方式限制我们View的大小。
  • EXACTLY:父View已经确定了View的确切大小。无论视图想要多大,它都会被赋予这些边界。
  • AT_MOST:视图可以任意大,直到指定的大小。

要确定视图的大小,可以使用 MeasureSpec.getSize() 和 MeasureSpec.getMode() 方法。

getSize() 方法返回以像素为单位的大小。

getMode() 方法返回测量模式:UNSPECIFIED,EXACTLY,AT_MOST。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  int desiredWidth = 100;
  int desiredHeight = 100;
  int widthMode = MeasureSpec.getMode(widthMeasureSpec);
  int widthSize = MeasureSpec.getSize(widthMeasureSpec);
  int heightMode = MeasureSpec.getMode(heightMeasureSpec);
  int heightSize = MeasureSpec.getSize(heightMeasureSpec);
  int width;
  int height;
  // Measure Width
  if (widthMode == MeasureSpec.EXACTLY) {
    // Must be this size
    width = widthSize;
  } else if (widthMode == MeasureSpec.AT_MOST) {
    // Can't be bigger than...
    width = Math.min(desiredWidth, widthSize);
  } else {
    // Be whatever you want
    width = desiredWidth;
  }
  // Measure Height
  if (heightMode == MeasureSpec.EXACTLY) {
    // Must be this size
    height = heightSize;
  } else if (heightMode == MeasureSpec.AT_MOST) {
    // Can't be bigger than...
    height = Math.min(desiredHeight, heightSize);
  } else {
    // Be whatever you want
    height = desiredHeight;
  }
  // MUST CALL THIS
  setMeasuredDimension(width, height);
}

onSizeChanged

调整视图大小时调用。

该方法在 onLayout() 之前调用,但在父 View 调用的 layout() 方法内部。layout() 方法调用 setFrame(),setFrame() 调用 onSizeChanged(),然后调用 onLayout()。

在 onSizeChanged 方法中,我们不能依赖子 View 来正确定位和调整大小。

onLayout

当视图的大小或位置发生更改时,将调用这些方法。

通常自定义视图在需要设置子View的大小时被覆盖。

onDraw

窗口上的大小和位置是为视图计算的,因此视图已准备好绘制。该方法接收一个 Canvas 对象,您可以向该对象设置命令以将它们发送到 GPU。

onFinishInflate

在所有子视图都添加到窗口后调用。但是当如下创建 视图 时,onFinishInflate 方法是不会被调用的。

new CustomView(context);

视图状态

View 提供了 onSaveInstanceState 和 onRestoreInstanceState 方法来保存 Bundle 中的某些状态。

视图更新

当我们需要以编程方式更改视图时,就会出现这种情况。为此,将调用 invalidate 和 requestLayout 方法。

invalidate() 重绘视图。

requestLayout() 调整视图大小。

触摸事件

用户正在交互的 Window 在 superDispatchTouchEvent 方法中接收事件。

// PhoneWindow.java
public boolean superDispatchTouchEvent(MotionEvent event) {
	return mDecor.superDispatchTouchEvent(event);
}

该事件作为 MotionEvent 对象传递。 MotionEvent 包含坐标、事件类型、事件时间和其他数据等数据。

Window 调度 DecorView。 DecorView 是一个 ViewGroup,因此它将通知其所有子视图该事件。这意味着我们为 Activity 指定的根容器将在 dispatchTouchEvent 方法中接收该事件。

对于 ViewGroup,我们可以重写 onInterceptTouchEvent 方法并在某些事件上返回true,从而不向子 View 发送任何事件。例如,ScrollView 不会向子 View 发送滚动事件。

如果我们不以任何方式重写 dispatchTouchEvent 方法中的逻辑,那么事件将到达顶部 View。反之如果 View 设置了 OnTouchListener,那么它是第一个有机会处理 MotionEvent 的。

接下来,我们沿着视图链向下查找,直到找到将处理 MotionEvent 的 View。

如果没有一个 View 处理了 MotionEvent 事件,则 Activity 有机会:

// Activity.java
public boolean onTouchEvent(MotionEvent event) {
  if (mWindow.shouldCloseOnTouch(this, event)) {
    finish();
    return true;
  }
  return false;
}

手势检测 (GestureDetector)

Android 有一个 GestureDetector 类,可以帮助处理 MotionEvent。在GestureDetector的帮助下,我们可以识别 singleTap、doubleTap、longPress、scroll 和 fling。

// GestureDetector.java
public interface OnGestureListener {
  boolean onDown(@NonNull MotionEvent e);
  void onShowPress(@NonNull MotionEvent e);
  boolean onSingleTapUp(@NonNull MotionEvent e);
  boolean onScroll(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float distanceX, float distanceY);
  void onLongPress(@NonNull MotionEvent e);
  boolean onFling(@NonNull MotionEvent e1, @NonNull MotionEvent e2, float velocityX, float velocityY);
}

使用 GestureDetector 的主要思想是不处理 OnTouchListener 中的事件类型,例如 ACTION_DOWN、ACTION_MOVE、ACTION_UP,我们将事件发送到 GestureDetector,它会为我们处理这些事件,这样,我们获得了一个方便的 API,它使我们能够根据手势了解用户执行的操作。

public class MainActivity extends AppCompatActivity {
  private GestureDetector mDetector;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // this is the view we will add the gesture detector to
    View myView = findViewById(R.id.my_view);
    // get the gesture detector
    mDetector = new GestureDetector(this, new MyGestureListener());
    // Add a touch listener to the view
    // The touch listener passes all its events on to the gesture detector
    myView.setOnTouchListener(touchListener);
  }
  // This touch listener passes everything on to the gesture detector.
  // That saves us the trouble of interpreting the raw touch events
  // ourselves.
  View.OnTouchListener touchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      // pass the events to the gesture detector
      // a return value of true means the detector is handling it
      // a return value of false means the detector didn't
      // recognize the event
      return mDetector.onTouchEvent(event);
    }
  };
  // In the SimpleOnGestureListener subclass you should override
  // onDown and any other gesture that you want to detect.
  class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
    @Override
    public boolean onDown(MotionEvent event) {
      Log.d("TAG","onDown: ");
      // don't return false here or else none of the other
      // gestures will work
      return true;
    }
    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
      Log.i("TAG", "onSingleTapConfirmed: ");
      return true;
    }
    @Override
    public void onLongPress(MotionEvent e) {
    	Log.i("TAG", "onLongPress: ");
    }
    @Override
    public boolean onDoubleTap(MotionEvent e) {
      Log.i("TAG", "onDoubleTap: ");
      return true;
    }
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
      Log.i("TAG", "onScroll: ");
      return true;
    }
    @Override
    public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
      Log.d("TAG", "onFling: ");
      return true;
    }
  }
}

此外,还有一个 ScaleGestureDetector 允许您定义缩放手势:

// ScaleGestureDetector.java
public interface OnScaleGestureListener {
  public boolean onScale(@NonNull ScaleGestureDetector detector);
  public boolean onScaleBegin(@NonNull ScaleGestureDetector detector);
  public void onScaleEnd(@NonNull ScaleGestureDetector detector);
}

ViewTreeObserver

Android 计算 View 的大小、放置和渲染等等会花费时间。而如果我们想找出 View 的某个值,可以通过添加 ViewTreeObserver 来接收有关视图准备就绪的事件。

ViewTreeObserver 允许您为视图树中的全局变化添加监听器。

例如:

container.getViewTreeObserver()
.addOnWindowAttachListener(new ViewTreeObserver.OnWindowAttachListener() {
  @Override
  public void onWindowAttached() {
  }
  @Override
  public void onWindowDetached() {
  }
});

相对的,监听器也有很多,例如:OnGlobalLayoutListener、OnWindowAttachListener、OnWindowFocusChangeListener 等等。

但是,请小心,因为有时 ViewTreeObserver 中的事件会被多次调用,因此在使用这些值之前以及注销 ViewTreeObserver 之前,请检查您是否确实设法读取了有意义的值。

此外,我们关注一下获取 ViewTreeObserver 的方法:

public ViewTreeObserver getViewTreeObserver() {
  if (mAttachInfo != null) {
  	return mAttachInfo.mTreeObserver;
  }
  if (mFloatingTreeObserver == null) {
  	mFloatingTreeObserver = new ViewTreeObserver(mContext);
  }
  return mFloatingTreeObserver;
}

在View中,为了检查View是否附加到Window上,会检查 mAttachInfo 是否为 null。AttachInfo mAttachInfo 是视图提供的有关窗口的一组信息。

如果我们没有将视图附加到窗口,则使用特殊的 ViewTreeObserver:mFloatingTreeObserver = new ViewTreeObserver(mContext)。

SurfaceView

SurfaceView 是一个视图,本身拥有 Surface。WindowManager 会为 SurfaceView 创建一个新的 Window 和 Surface。 SurfaceView 的主要优点是我们可以在单独的线程中执行繁重的图形计算。

RenderThread

RenderThread 负责将 DisplayList 转换为 OpenGL 命令并发送给 GPU。

DisplayList 是一系列定义输出图像的图形命令,这些图像随后被转换为 GPU 可以理解的 OpenGL 命令。GPU 不知道什么是动画,它只能理解基本命令,例如:

translation(x,y,z)
rotate(x,y)
// or basic drawing utilities:
drawCircle(centerX, centerY, radius, paint)
drawRoundRect(left, top, right, bottom, cornerRadiusX, cornerRadiusY, paint)

由于视图的复杂性,所以会创建大量的 DisplayList,这些命令一起形成了我们在屏幕上看到的复杂动画。

渲染分两个阶段进行:

  • View.draw() 在 UI 线程上执行。
  • DrawFrame 在 RenderThread 中执行,该线程基于 View.draw() 进行工作。

RenderThread 只执行 onDraw() 渲染,UI Thread 执行 onMeasure()、onLayout() 等。这种分割背后的概念是在不渲染阻塞的情况下完成测量和计算其他事情的艰苦工作,从而获得平滑的 fps。

当RenderThread正在渲染时,UI线程可以为下一帧准备数据。

#文章首发挑战赛#

相关推荐

服务器数据恢复—Raid5数据灾难不用愁,Raid5数据恢复原理了解下

Raid5数据恢复算法原理:分布式奇偶校验的独立磁盘结构(被称之为raid5)的数据恢复有一个“奇偶校验”的概念。可以简单的理解为二进制运算中的“异或运算”,通常使用的标识是xor。运算规则:若二者值...

服务器数据恢复—多次异常断电导致服务器raid不可用的数据恢复

服务器数据恢复环境&故障:由于机房多次断电导致一台服务器中raid阵列信息丢失。该阵列中存放的是文档,上层安装的是Windowsserver操作系统,没有配置ups。因为服务器异常断电重启后,rai...

服务器数据恢复-V7000存储更换磁盘数据同步失败的数据恢复案例

服务器数据恢复环境:P740+AIX+Sybase+V7000存储,存储阵列柜上共12块SAS机械硬盘(其中一块为热备盘)。服务器故障:存储阵列柜中有磁盘出现故障,工作人员发现后更换磁盘,新更换的磁盘...

「服务器数据恢复」重装系统导致XFS文件系统分区丢失的数据恢复

服务器数据恢复环境:DellPowerVault系列磁盘柜;用RAID卡创建的一组RAID5;分配一个LUN。服务器故障:在Linux系统层面对LUN进行分区,划分sdc1和sdc2两个分区。将sd...

服务器数据恢复-ESXi虚拟机被误删的数据恢复案例

服务器数据恢复环境:一台服务器安装的ESXi虚拟化系统,该虚拟化系统连接了多个LUN,其中一个LUN上运行了数台虚拟机,虚拟机安装WindowsServer操作系统。服务器故障&分析:管理员因误操作...

「服务器数据恢复」Raid5阵列两块硬盘亮黄灯掉线的数据恢复案例

服务器数据恢复环境:HPStorageWorks某型号存储;虚拟化平台为vmwareexsi;10块磁盘组成raid5(有1块热备盘)。服务器故障:raid5阵列中两块硬盘指示灯变黄掉线,无法读取...

服务器数据恢复—基于oracle数据库的SAP数据恢复案例

服务器存储数据恢复环境:某品牌服务器存储中有一组由6块SAS硬盘组建的RAID5阵列,其中有1块硬盘作为热备盘使用。上层划分若干lun,存放Oracle数据库数据。服务器存储故障&分析:该RAID5阵...

「服务器虚拟化数据恢复」Xen Server环境下数据库数据恢复案例

服务器虚拟化数据恢复环境:Dell某型号服务器;数块STAT硬盘通过raid卡组建的RAID10;XenServer服务器虚拟化系统;故障虚拟机操作系统:WindowsServer,部署Web服务...

服务器数据恢复—RAID故障导致oracle无法启动的数据恢复案例

服务器数据恢复环境:某品牌服务器中有一组由4块SAS磁盘做的RAID5磁盘阵列。该服务器操作系统为windowsserver,运行了一个单节点Oracle,数据存储为文件系统,无归档。该oracle...

服务器数据恢复—服务器磁盘阵列常见故障表现&amp;解决方案

RAID(磁盘阵列)是一种将多块物理硬盘整合成一个虚拟存储的技术,raid模块相当于一个存储管理的中间层,上层接收并执行操作系统及文件系统的数据读写指令,下层管理数据在各个物理硬盘上的存储及读写。相对...

「服务器数据恢复」IBM某型号服务器RAID5磁盘阵列数据恢复案例

服务器数据恢复环境:IBM某型号服务器;5块SAS硬盘组成RAID5磁盘阵列;存储划分为1个LUN和3个分区:第一个分区存放windowsserver系统,第二个分区存放SQLServer数据库,...

服务器数据恢复—Zfs文件系统下误删除文件如何恢复数据?

服务器故障:一台zfs文件系统服务器,管理员误操作删除服务器上的数据。服务器数据恢复过程:1、将故障服务器所有磁盘编号后取出,硬件工程师检测所有硬盘后没有发现有磁盘存在硬件故障。以只读方式将全部磁盘做...

服务器数据恢复—Linux+raid5服务器数据恢复案例

服务器数据恢复环境:某品牌linux操作系统服务器,服务器中有4块SAS接口硬盘组建一组raid5阵列。服务器中存放的数据有数据库、办公文档、代码文件等。服务器故障&检测:服务器在运行过程中突然瘫痪,...

服务器数据恢复—Sql Server数据库数据恢复案例

服务器数据恢复环境:一台安装windowsserver操作系统的服务器。一组由8块硬盘组建的RAID5,划分LUN供这台服务器使用。在windows服务器内装有SqlServer数据库。存储空间LU...

服务器数据恢复—阿里云ECS网站服务器数据恢复案例

云服务器数据恢复环境:阿里云ECS网站服务器,linux操作系统+mysql数据库。云服务器故障:在执行数据库版本更新测试时,在生产库误执行了本来应该在测试库执行的sql脚本,导致生产库部分表被tru...

取消回复欢迎 发表评论: