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

Android Framework核心:Window窗口概念

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

#文章首发挑战赛#

相关推荐

0722-6.2.0-如何在RedHat7.2使用rpm安装CDH(无CM)

文档编写目的在前面的文档中,介绍了在有CM和无CM两种情况下使用rpm方式安装CDH5.10.0,本文档将介绍如何在无CM的情况下使用rpm方式安装CDH6.2.0,与之前安装C5进行对比。环境介绍:...

ARM64 平台基于 openEuler + iSula 环境部署 Kubernetes

为什么要在arm64平台上部署Kubernetes,而且还是鲲鹏920的架构。说来话长。。。此处省略5000字。介绍下系统信息;o架构:鲲鹏920(Kunpeng920)oOS:ope...

生产环境starrocks 3.1存算一体集群部署

集群规划FE:节点主要负责元数据管理、客户端连接管理、查询计划和查询调度。>3节点。BE:节点负责数据存储和SQL执行。>3节点。CN:无存储功能能的BE。环境准备CPU检查JDK...

在CentOS上添加swap虚拟内存并设置优先级

现如今很多云服务器都会自己配置好虚拟内存,当然也有很多没有配置虚拟内存的,虚拟内存可以让我们的低配服务器使用更多的内存,可以减少很多硬件成本,比如我们运行很多服务的时候,内存常常会满,当配置了虚拟内存...

国产深度(deepin)操作系统优化指南

1.升级内核随着deepin版本的更新,会自动升级系统内核,但是我们依旧可以通过命令行手动升级内核,以获取更好的性能和更多的硬件支持。具体操作:-添加PPAs使用以下命令添加PPAs:```...

postgresql-15.4 多节点主从(读写分离)

1、下载软件[root@TX-CN-PostgreSQL01-252software]#wgethttps://ftp.postgresql.org/pub/source/v15.4/postg...

Docker 容器 Java 服务内存与 GC 优化实施方案

一、设置Docker容器内存限制(生产环境建议)1.查看宿主机可用内存bashfree-h#示例输出(假设宿主机剩余16GB可用内存)#Mem:64G...

虚拟内存设置、解决linux内存不够问题

虚拟内存设置(解决linux内存不够情况)背景介绍  Memory指机器物理内存,读写速度低于CPU一个量级,但是高于磁盘不止一个量级。所以,程序和数据如果在内存的话,会有非常快的读写速度。但是,内存...

Elasticsearch性能调优(5):服务器配置选择

在选择elasticsearch服务器时,要尽可能地选择与当前业务量相匹配的服务器。如果服务器配置太低,则意味着需要更多的节点来满足需求,一个集群的节点太多时会增加集群管理的成本。如果服务器配置太高,...

Es如何落地

一、配置准备节点类型CPU内存硬盘网络机器数操作系统data节点16C64G2000G本地SSD所有es同一可用区3(ecs)Centos7master节点2C8G200G云SSD所有es同一可用区...

针对Linux内存管理知识学习总结

现在的服务器大部分都是运行在Linux上面的,所以,作为一个程序员有必要简单地了解一下系统是如何运行的。对于内存部分需要知道:地址映射内存管理的方式缺页异常先来看一些基本的知识,在进程看来,内存分为内...

MySQL进阶之性能优化

概述MySQL的性能优化,包括了服务器硬件优化、操作系统的优化、MySQL数据库配置优化、数据库表设计的优化、SQL语句优化等5个方面的优化。在进行优化之前,需要先掌握性能分析的思路和方法,找出问题,...

Linux Cgroups(Control Groups)原理

LinuxCgroups(ControlGroups)是内核提供的资源分配、限制和监控机制,通过层级化进程分组实现资源的精细化控制。以下从核心原理、操作示例和版本演进三方面详细分析:一、核心原理与...

linux 常用性能优化参数及理解

1.优化内核相关参数配置文件/etc/sysctl.conf配置方法直接将参数添加进文件每条一行.sysctl-a可以查看默认配置sysctl-p执行并检测是否有错误例如设置错了参数:[roo...

如何在 Linux 中使用 Sysctl 命令?

sysctl是一个用于配置和查询Linux内核参数的命令行工具。它通过与/proc/sys虚拟文件系统交互,允许用户在运行时动态修改内核参数。这些参数控制着系统的各种行为,包括网络设置、文件...

取消回复欢迎 发表评论: