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

Android Framework核心:Window窗口概念

nanshan 2024-11-20 19:25 10 浏览 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线程可以为下一帧准备数据。

#文章首发挑战赛#

相关推荐

如何为MySQL服务器和客户机启用SSL?

用户想要与MySQL服务器建立一条安全连接时,常常依赖VPN隧道或SSH隧道。不过,获得MySQL连接的另一个办法是,启用MySQL服务器上的SSL封装器(SSLwrapper)。这每一种方法各有其...

Mysql5.7 出现大量 unauthenticated user

线上环境mysql5.7突然出现大量unauthenticateduser,进mysql,showprocesslist;解决办法有:在/etc/hosts中添加客户端ip,如192.16...

MySQL 在 Windows 系统下的安装(mysql安装教程windows)

更多技术文章MySQL在Windows系统下的安装1.下载mysql和Framework链接链接:百度网盘请输入提取码提取码:6w3p双击mysql-installer-communit...

MySql5.7.21.zip绿色版安装(mysql数据库绿色版安装)

1、去网上下载满足系统要求的版本(mysql-5.7.21-winx64.zip)2、直接解压3、mysql的初始化(1)以管理员身份运行cmd,在mysql中的bin目录下shift+右键-在...

MySQL(8.0)中文全文检索 (亲测有效)

在一堆文字中找到含有关键字的应用。当然也可以用以下语句实现:SELECT*FROM<表名>WHERE<字段名>like‘%ABC%’但是它的效率太低,是全盘扫描。...

新手教程,Linux系统下MySQL的安装

看了两三个教程。终于在哔哩哔哩找到一个简单高效的教程,成功安装,up主名叫bili逍遥bili,感兴趣可以去看看。下面这个是我总结的安装方法环境:CentOS764位1.下载安装包,个人觉得在...

麒麟服务器操作系统安装 MySQL 8 实战指南

原文连接:「链接」Hello,大家好啊,今天给大家带来一篇麒麟服务器操作系统上安装MySQL8的文章,欢迎大家分享点赞,点个在看和关注吧!MySQL作为主流开源数据库之一,被广泛应用于各种业务...

用Python玩转MySQL的全攻略,从环境搭建到项目实战全解析

这是一篇关于“MySQL数据库入门实战-Python版”的教程,结合了案例实战分析,帮助初学者快速掌握如何使用Python操作MySQL数据库。一、环境准备1.安装Python访问Pytho...

安装MySQL(中标麒麟 安装mysql)

安装MySQL注意:一定要用root用户操作如下步骤;先卸载MySQL再安装1.安装包准备(1)查看MySQL是否安装rpm-qa|grepmysql(2)如果安装了MySQL,就先卸载rpm-...

Mysql最全笔记,快速入门,干货满满,爆肝

目录一、MySQL的重要性二、MySQL介绍三、软件的服务架构四、MySQL的安装五、SQL语句六、数据库相关(DDL)七、表相关八、DML相关(表中数据)九、DQL(重点)十、数据完...

MAC电脑安装MySQL操作步骤(mac安装mysqldb)

1、在官网下载MySQL:https://dev.mysql.com/downloads/mysql/根据自己的macOS版本,选择适配的MySQL版本根据自己需求选择相应的安装包,我这里选择macO...

mysql主从(mysql主从切换)

1、本章面试题什么是mysql主从,主从有什么好处什么是读写分离,有什么好处,使用mycat如何实现2、知识点2.1、课程回顾dubboORM->MVC->RPC->SOApro...

【linux学习】以MySQL为例,带你了解数据库

做运维的小伙伴在日常工作中难免需要接触到数据库,不管是MySQL,mariadb,达梦还是瀚高等其实命令都差不多,下面我就以MySQL为例带大家一起来了解下数据库。有兴趣的小伙伴不妨评论区一起交流下...

玩玩WordPress - 环境简介(0)(玩玩网络科技有限公司)

简介提到开源博客系统,一般都会直接想到WordPress!WordPress是使用PHP开发的,数据库使用的是MySQL,一般会在Linux上运行,Nginx作为前端。这时候就需要有一套LNMP(Li...

服务器常用端口都有哪些?(服务器端使用的端口号范围)

下面为大家介绍一下,服务器常用的一些默认端口,以及他们的作用:  21:FTP服务所开放的端口,用于上传、下载文件。  22:SSH端口,用于通过命令行模式远程连接Linux服务器或vps。  23:...

取消回复欢迎 发表评论: