ANativeWindow和Surface的关系(Native层)

709 阅读1分钟

在Native层, Surface.cpp类继承自ANativeWindow,具体代码如下

# aosp/frameworks/native/libs/gui/include/gui/Surface.h

class Surface: public ANativeObjectBase<ANativeWindow, Surface, RefBase> {
  ......
}

# aosp/frameworks/native/libs/ui/include/ui/ANativeObjectBase.h
template <typename NATIVE_TYPE, typename TYPE, typename REF, typename NATIVE_BASE = android_native_base_t>
class ANativeObjectBase : public NATIVE_TYPE, public REF {
  ......
}

故而在native层可以通过Surface接口,转换获取到ANativeWindow

sp<ANativeWindow> android_view_Surface_getNativeWindow(JNIEnv* env, jobject surfaceObj) {
      return android_view_Surface_getSurface(env, surfaceObj);
}

// 强制转换mNativeObject
sp<Surface> android_view_Surface_getSurface(JNIEnv* env, jobject surfaceObj) {
      sp<Surface> sur;
      jobject lock = env->GetObjectField(surfaceObj,
              gSurfaceClassInfo.mLock);
      if (env->MonitorEnter(lock) == JNI_OK) {
          sur = reinterpret_cast<Surface *>(
                  env->GetLongField(surfaceObj, gSurfaceClassInfo.mNativeObject));
          env->MonitorExit(lock);
      }
      env->DeleteLocalRef(lock);
      return sur;
}