android graphic(10)—activity申请surface流程

来源:互联网 发布:类似prezi的软件 编辑:程序博客网 时间:2024/06/15 05:54

 

http://blog.csdn.net/lewif/article/details/50735460

目录(?)[+]

  • create new Activity
    • newActivity
    • setContentView
  • handleResumeActivity

Android中启动一个Activity的函数为handleLaunchActivity()

  privatevoidhandleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
 
    //新建一个Activity,并调用其onCreate()方法等
    Activity a = performLaunchActivity(r, customIntent);
 
        // 调用handleResumeActivity
    handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);
 
 
 
  }

主要包括2部分: 
1.
新建一个Activity,同时调用其onCreate等函数,我们知道在onCreate函数中,一般会调用setContentView(View)去给Activity添加一个View 
2.
调用handleResumeActivity 
下面逐步分析其中发生的事情,

create new Activity

Activity a = performLaunchActivity(r, customIntent);
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
 
    Activity activity = null;
    //通过Activity的类名,利用java反射机制来创建对应的Activity
    activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
        //调用ActivityonCreate函数            
    mInstrumentation.callActivityOnCreate(activity, r.state);
}

上面主要包括2部分: 
1.
通过Activity的类名,利用Java反射机制来创建对应的Activity 
2.
调用ActivityonCreate函数,进而调用onCreate中的setContentView(myView)

newActivity

首先,在Instrumentation类中重载了newActivity函数,最终实现的功能是相同的,这里分析另外一个newActivity函数,

    public Activity newActivity(Class<?> clazz, Context context, 
            IBinder token, Application application, Intent intent, ActivityInfo info, 
            CharSequence title, Activity parent, String id,
            Object lastNonConfigurationInstance) throws InstantiationException, 
            IllegalAccessException {
        //新建一个Activity 
        Activity activity = (Activity)clazz.newInstance();
        ActivityThread aThread = null;
        //activity attach到一个window
        activity.attach(context, aThread, this, token, application, intent,
                info, title, parent, id,
                (Activity.NonConfigurationInstances)lastNonConfigurationInstance,
                new Configuration());
        return activity;
    }

主要包括2部分: 
1.
载入Activity类,新建一个Activity对象; 
2.
调用attach,填充新建的Activity中的成员。 
主要分析attach函数,

    final void attach(Context context, ActivityThread aThread, Instrumentation instr, IBinder token,
            Application application, Intent intent, ActivityInfo info, CharSequence title, 
            Activity parent, String id, NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config) {
        attach(context, aThread, instr, token, 0, application, intent, info, title, parent, id,
            lastNonConfigurationInstances, config);
    }
final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config) {
 
//填充Activity.mWindow,就是个PhoneWindow
mWindow = PolicyManager.makeNewWindow(this);
 
//填充Activity.mWindow.mWindowManager,就是个WindowManagerImpl
mWindow.setWindowManager(
                (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                mToken, mComponent.flattenToString(),
                (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
 
//  填充Activity.mWindowManager,就是个WindowManagerImpl
mWindowManager = mWindow.getWindowManager();
    publicvoidsetWindowManager(WindowManager wm, IBinder appToken, String appName) {
        setWindowManager(wm, appToken, appName, false);
    }
  publicvoidsetWindowManager(WindowManager wm, IBinder appToken, String appName,
            boolean hardwareAccelerated) {
        mAppToken = appToken;
        mAppName = appName;
        mHardwareAccelerated = hardwareAccelerated
                || SystemProperties.getBoolean(PROPERTY_HARDWARE_UI, false);
        if (wm == null) {
            wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        }
        mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
    }

关于Context.WINDOW_SERVICE

        registerService(WINDOW_SERVICE, new ServiceFetcher() {
                Display mDefaultDisplay;
                //这里是重写了getService函数,直接返回new一个WindowManagerImpl
                public Object getService(ContextImpl ctx) {
                    Display display = ctx.mDisplay;
                    if (display == null) {
                        if (mDefaultDisplay == null) {
                            DisplayManager dm = (DisplayManager)ctx.getOuterContext().
                                    getSystemService(Context.DISPLAY_SERVICE);
                            mDefaultDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY);
                        }
                        display = mDefaultDisplay;
                    }
                    returnnew WindowManagerImpl(display);
                }});

通过attach函数后,Activity中的成员填充情况如下,

而,

所以,

setContentView

下面分析setContentView函数发生了什么,

    publicvoidsetContentView(View view) {
        getWindow().setContentView(view);
        initActionBar();
    }
    public Window getWindow() {
        return mWindow;
    }

进而调用PhoneWindowsetContentView

    publicvoidsetContentView(View view) {
        setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
    }
    publicvoidsetContentView(View view, ViewGroup.LayoutParams params) {
        //class ViewGroup extends View implements ViewParent, ViewManager 
        //如果mContentParent 为空,调用installDecor
        if (mContentParent == null) {
            installDecor();
        } else {
            mContentParent.removeAllViews();
        }
        //myview添加到mContentParent
        mContentParent.addView(view, params);
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
    }

上面主要包括2部分: 
1.
如果PhoneWindow.mContentParent为空,调用installDecor,看来会对mContentParent赋值,然后还要install一个decor 
2.
myView添加到mContentParent

 private void installDecor() {
            // This is the top-level view of the window, containing the window decor.
         // private DecorView mDecor;
         //mDecor是一个window中最顶层的view,包含了window的装饰
        //生成mDecor 
        if (mDecor == null) {
            mDecor = generateDecor();
       }
         // This is the view in which the window contents are placed. It is either
    // mDecor itself, or a child of mDecor where the contents go.
         //mContentParent 是放window中内容的地方,也就是你添加的各种view
         //它是DecorView本身,或者是DecorView child
        //private ViewGroup mContentParent;
        if (mContentParent == null) {
            mContentParent = generateLayout(mDecor);
         
}
    protected DecorView generateDecor() {
        //new一个DecorView
        returnnew DecorView(getContext(), -1);
    }
protected ViewGroup generateLayout(DecorView decor) {
 
     //DecorView中添加一个view
         View in = mLayoutInflater.inflate(layoutResource, null);
        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
         // contentParent 其实就是线程布局,ID_ANDROID_CONTENT
         // findViewById也是从DecorView中寻找
         //所以contentParent是填充在DecorView中的
      ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
    public View findViewById(int id) {
        return getDecorView().findViewById(id);
    }

Activity调用完setContentView后,其mWindow,即PhoneWindow中现存的View如下图所示,

handleResumeActivity

 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward,
            boolean reallyResume) {
            final Activity a = r.activity;
             if (r.window == null && !a.mFinished && willBeVisible) {
                //返回mWindow,就是个PhoneWindow
                r.window = r.activity.getWindow();
                //返回dector
                View decor = r.window.getDecorView();
                decor.setVisibility(View.INVISIBLE);
                //WindowManagerImpl
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                if (a.mVisibleFromClient) {
                    a.mWindowAdded = true;
                    //调用WindowManagerImpl去添加decorview
                    wm.addView(decor, l);
                }
    }
    //windowmanagerimpladdView
        publicvoidaddView(View view, ViewGroup.LayoutParams params) {
    //
        mGlobal.addView(view, params, mDisplay, mParentWindow);
    }
    //sDefaultWindowManagerstatic,类数据
    publicstatic WindowManagerGlobal getInstance() {
        synchronized (WindowManagerGlobal.class) {
            if (sDefaultWindowManager == null) {
                sDefaultWindowManager = new WindowManagerGlobal();
            }
            return sDefaultWindowManager;
        }
    }
    //windowmanagerglobaladdView
     publicvoidaddView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        ViewRootImpl root;
        View panelParentView = null;
 
        //新建一个ViewRootImpl,并将其添加到windowmanagerglobalmRoots
            root = new ViewRootImpl(view.getContext(), display);
 
            view.setLayoutParams(wparams);
 
        //private final ArrayList<View> mViews = new ArrayList<View>();
       //将参数的view,即mDecor添加到windowmanagerglobalmViews
            mViews.add(view);
 
      //private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();
    //windowmanagerglobalmRoots
    mRoots.add(root);
        mParams.add(wparams);
        }
 
 
    //重要:将dector添加到root这个ViewRootImpl
        // do this last because it fires off messages to start doing things
        try {
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
        }
    }

上面主要包括2部分: 
1.new
一个ViewRootImpl,并将其添加到windowmanagerglobalmRoots,将mDecor添加到windowmanagerglobalmViews 
2.
dector添加到root这个ViewRootImpl

 publicViewRootImpl(Context context, Display display) {
     //final IWindowSession mWindowSession;
     mWindowSession = WindowManagerGlobal.getWindowSession();
     //class W extends IWindow.Stub 
     //创建一个W ,服务端
     mWindow = new W(this);
 }

ViewRootImpl的构造函数中,主要构建了IWindowSession的代理端,而服务端就是WindowManagerService;创建了一个IWindow的服务端。此外在类ViewRootImpl中有个成员变量为mSurface,调用了无参的Surface构造函数。

 privatefinal Surface mSurface = new Surface();
    publicstatic IWindowSession getWindowSession() {
        synchronized (WindowManagerGlobal.class) {
            if (sWindowSession == null) {
                try {
                    InputMethodManager imm = InputMethodManager.getInstance();
                    //获取WindowManagerService的代理对象
                    IWindowManager windowManager = getWindowManagerService();
                    //private static IWindowSession sWindowSession;
                    //sWindowSession static 
                    //调用openSession,返回WindowSession的代理对象
                    sWindowSession = windowManager.openSession(
                            imm.getClient(), imm.getInputContext());
                    float animatorScale = windowManager.getAnimationScale(2);
                    ValueAnimator.setDurationScale(animatorScale);
                } catch (RemoteException e) {
                    Log.e(TAG, "Failed to open window session", e);
                }
            }
            return sWindowSession;
        }
    }
    publicstatic IWindowManager getWindowManagerService() {
        synchronized (WindowManagerGlobal.class) {
            if (sWindowManagerService == null) {
                 //sWindowManagerServicestatic
                //private static IWindowManager sWindowManagerService;
                //获取WindowManagerService的代理对象
                sWindowManagerService = IWindowManager.Stub.asInterface(
                        ServiceManager.getService("window"));
            }
            return sWindowManagerService;
        }
    }
    //WindowManagerService所在进程创建一个new Session,匿名binder
    @Override
    public IWindowSession openSession(IInputMethodClient client,
            IInputContext inputContext) {
        Session session = new Session(this, client, inputContext);
        return session;
    }

下面分析root.setView(view,wparams, panelParentView);,既是调用ViewRootImplsetView(),

 
    /**
     * We have one child
     */
    publicvoidsetView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
     //首先mView就是DecorView,只被赋值一次,将DecorViewViewRootImpl联系
     if (mView == null) {
      mView = view;
     //调用requestLayout
      requestLayout();
          //调用addToDisplay
          res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mInputChannel); 
}
}

首先分析addToDisplay,进而调用Session.addToDisplay()mWindowIWindowserver端,

       publicintaddToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
            int viewVisibility, int displayId, Rect outContentInsets,
            InputChannel outInputChannel) {
        return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId,
                outContentInsets, outInputChannel);
    }

—>WindowManagerService.addWindow()

    //WindowManagerService中为IWindowclient
    publicint addWindow(Session session, IWindow client, int seq,
            WindowManager.LayoutParams attrs, int viewVisibility, int displayId,
            Rect outContentInsets, InputChannel outInputChannel) {
                       //创建一个WindowState
            win = new WindowState(this, session, client, token,
                    attachedWindow, appOp[0], seq, attrs, viewVisibility, displayContent);
            //调用WindowStateattach      
            win.attach();
            // final HashMap<IBinder, WindowState> mWindowMap = new HashMap<IBinder, WindowState>();
            // HashMapIWindow的代理和WindowState
            mWindowMap.put(client.asBinder(), win);         
 
            }
         void attach() {
        if (WindowManagerService.localLOGV) Slog.v(
            TAG, "Attaching " + this + " token=" + mToken
            + ", list=" + mToken.windows);
        mSession.windowAddedLocked();
    }
    void windowAddedLocked() {
        if (mSurfaceSession == null) {
            //创建一个SurfaceSession
            mSurfaceSession = new SurfaceSession();
            //mSession保存到WindowManagerServicemSessions
            mService.mSessions.add(this);
        }
        mNumWindow++;
    }

SurfaceComposerClient专门用来和surface flinger建立connectionISurfaceComposerClientSurfaceComposerClientclient,而surface flinger中的serverClientSurfaceSession就是SurfaceComposerClientjava层的代表,其mNativeClient成员就是native层的SurfaceComposerClient对象的指针。

    /** Create a new connection with the surface flinger. */
    publicSurfaceSession() {
        mNativeClient = nativeCreate();
    }
static jint nativeCreate(JNIEnv* env, jclass clazz) {
    SurfaceComposerClient* client = new SurfaceComposerClient();
    client->incStrong((void*)nativeCreate);
    returnreinterpret_cast<jint>(client);
}
SurfaceComposerClient::SurfaceComposerClient()
    : mStatus(NO_INIT), mComposer(Composer::getInstance())
{
}
void SurfaceComposerClient::onFirstRef() {
    sp<ISurfaceComposer> sm(ComposerService::getComposerService());
    if (sm !=0) {
        //surface fligner建立联系
        sp<ISurfaceComposerClient> conn = sm->createConnection();
        if (conn !=0) {
            mClient = conn;
            mStatus = NO_ERROR;
        }
    }
}
classBpSurfaceComposer : public BpInterface<ISurfaceComposer>
{
    virtual sp<ISurfaceComposerClient> createConnection()
    {
        uint32_t n;
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
        remote()->transact(BnSurfaceComposer::CREATE_CONNECTION, data, &reply);
        return interface_cast<ISurfaceComposerClient>(reply.readStrongBinder());
    }
}
status_tBnSurfaceComposer::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
    {
            caseCREATE_CONNECTION: {
            CHECK_INTERFACE(ISurfaceComposer, data, reply);
            sp<IBinder> b = createConnection()->asBinder();
            reply->writeStrongBinder(b);
            return NO_ERROR;
        }
    }

surfaceflinger—>createConnection()surfaceflinger中对应的newClient(this)

sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
{
    sp<ISurfaceComposerClient> bclient;
    sp<Client> client(new Client(this));
    status_t err = client->initCheck();
    if (err == NO_ERROR) {
        bclient = client;
    }
    return bclient;
}

requestLayout()—>doTraversal()—>performTraversals()

    privatevoidperformTraversals() {
        //调用relayoutWindow,创建surface
        relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
        //layerCanvas上画图
        mView.draw(layerCanvas);
    }     

主要是relayoutWindow()函数,返回填充的mSurface,这个mSurface其实主要是对应nativeSurface对象,有了surface就能dequeue buffer了,然后再去画图啥的。

  privateintrelayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
            boolean insetsPending) throws RemoteException {
            //binder,调用Sessionrelayout,返回填充的mSurface
               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,
                mPendingConfiguration, mSurface);     
            

利用IWindowSessionSession通信,调用relayout,注意,这里mSurfaceViewRootImpl的成员变量,开始调用了无参的构造函数,IWindowSession.aidl文件中,mSurface是被out修饰,因此是在server端创建,然后再binder返回给ViewRootImpl 
Session—>relayout
(),

   publicintrelayout(IWindow window, int seq, WindowManager.LayoutParams attrs,
            int requestedWidth, int requestedHeight, int viewFlags,
            int flags, Rect outFrame, Rect outOverscanInsets, Rect outContentInsets,
            Rect outVisibleInsets, Configuration outConfig, Surface outSurface) {
        int res = mService.relayoutWindow(this, window, seq, attrs,
                requestedWidth, requestedHeight, viewFlags, flags,
                outFrame, outOverscanInsets, outContentInsets, outVisibleInsets,
                outConfig, outSurface);
        return res;
    }

Session—>relayout()—>WindowManagerService.relayoutWindow,

        publicintrelayoutWindow(Session session, IWindow client, int seq,
            WindowManager.LayoutParams attrs, int requestedWidth,
            int requestedHeight, int viewVisibility, int flags,
            Rect outFrame, Rect outOverscanInsets, Rect outContentInsets,
            Rect outVisibleInsets, Configuration outConfig, Surface outSurface) {
 
            //新建一个SurfaceControl 
            SurfaceControl surfaceControl = winAnimator.createSurfaceLocked();
                    if (surfaceControl != null) {
                        outSurface.copyFrom(surfaceControl);
                        if (SHOW_TRANSACTIONS) Slog.i(TAG,
                                "  OUT SURFACE " + outSurface + ": copied");
                    } else {
                        // For some reason there isn't a surface.  Clear the
                        // caller's object so they see the same state.
                        outSurface.release();
                    }
            }

首先创建一个SurfaceControl

    SurfaceControl createSurfaceLocked() {
 
            mSurfaceControl = new SurfaceControl(
                        mSession.mSurfaceSession,
                        attrs.getTitle().toString(),
                        w, h, format, flags);
             }
    publicSurfaceControl(SurfaceSession session,
            String name, int w, int h, int format, int flags)
                    throws OutOfResourcesException {
              //session就是SurfaceComposerClientjava层的代表
              //mNativeObjectnativeSurfaceControl的指针
    mNativeObject = nativeCreate(session, name, w, h, format, flags);
    }
static jint nativeCreate(JNIEnv* env, jclass clazz, jobject sessionObj,
        jstring nameStr, jint w, jint h, jint format, jint flags) {
    ScopedUtfChars name(env, nameStr);
    //从上层取到SurfaceComposerClient的指针,还原一个SurfaceComposerClient
    sp<SurfaceComposerClient> client(android_view_SurfaceSession_getClient(env, sessionObj));
    //调用createSurface,返回的是一个SurfaceControl对象,注意不是surface
    sp<SurfaceControl> surface = client->createSurface(
            String8(name.c_str()), w, h, format, flags);
    if (surface == NULL) {
        jniThrowException(env, OutOfResourcesException, NULL);
        return0;
    }
    surface->incStrong((void *)nativeCreate);
    //返回给javaSurfaceControl的指针
    returnint(surface.get());
}
sp<SurfaceControl> SurfaceComposerClient::createSurface(
        const String8& name,
        uint32_t w,
        uint32_t h,
        PixelFormat format,
        uint32_t flags)
{
    sp<SurfaceControl> sur;
    if (mStatus == NO_ERROR) {
        sp<IBinder>handle;
        sp<IGraphicBufferProducer> gbp;
        status_t err = mClient->createSurface(name, w, h, format, flags,
                &handle, &gbp);
        //gbp就是surfaceflignerLayermBufferQueueclient(IGraphicBufferProducer) 
        if (err == NO_ERROR) {
            sur =new SurfaceControl(this, handle, gbp);
        }
    }
    return sur;
}
classBpSurfaceComposerClient : public BpInterface<ISurfaceComposerClient>
{
    virtual status_t createSurface(constString8& name, uint32_tw,
            uint32_th, PixelFormatformat, uint32_tflags,
            sp<IBinder>* handle,
            sp<IGraphicBufferProducer>* gbp) {
        Parcel data, reply;
        data.writeInterfaceToken(ISurfaceComposerClient::getInterfaceDescriptor());
        data.writeString8(name);
        data.writeInt32(w);
        data.writeInt32(h);
        data.writeInt32(format);
        data.writeInt32(flags);
        remote()->transact(CREATE_SURFACE, data, &reply);
        *handle = reply.readStrongBinder();
        //gbp就是surfaceflignerLayermBufferQueueclient
        *gbp = interface_cast<IGraphicBufferProducer>(reply.readStrongBinder());
        return reply.readInt32();
    }
}
status_tBnSurfaceComposerClient::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
    
            caseCREATE_SURFACE: {
            CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
            String8 name = data.readString8();
            uint32_t w = data.readInt32();
            uint32_t h = data.readInt32();
            PixelFormat format = data.readInt32();
            uint32_t flags = data.readInt32();
            sp<IBinder> handle;
            sp<IGraphicBufferProducer> gbp;
            status_t result = createSurface(name, w, h, format, flags,
                    &handle, &gbp);
            reply->writeStrongBinder(handle);
            reply->writeStrongBinder(gbp->asBinder());
            reply->writeInt32(result);
            return NO_ERROR;
        } break;
    

Client—>createSurface()

status_t Client::createSurface(
        const String8& name,
        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
        sp<IBinder>* handle,
        sp<IGraphicBufferProducer>* gbp)
{
    /*
     * createSurface must be called from the GL thread so that it can
     * have access to the GL context.
     */
 
    class MessageCreateLayer : public MessageBase {
        SurfaceFlinger* flinger;
        Client* client;
        sp<IBinder>* handle;
        sp<IGraphicBufferProducer>* gbp;
        status_t result;
        const String8& name;
        uint32_t w, h;
        PixelFormat format;
        uint32_t flags;
    public:
        MessageCreateLayer(SurfaceFlinger* flinger,
                const String8& name, Client* client,
                uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
                sp<IBinder>* handle,
                sp<IGraphicBufferProducer>* gbp)
            : flinger(flinger), client(client),
              handle(handle), gbp(gbp),
              name(name), w(w), h(h), format(format), flags(flags) {
        }
        status_t getResult() const { return result; }
        virtualbool handler() {
            result = flinger->createLayer(name, client, w, h, format, flags,
                    handle, gbp);
            returntrue;
        }
    };
 
    sp<MessageBase> msg = new MessageCreateLayer(mFlinger.get(),
            name, this, w, h, format, flags, handle, gbp);
    mFlinger->postMessageSync(msg);
    return static_cast<MessageCreateLayer*>( msg.get() )->getResult();
}

进而调用flinger.createLayer()—>Layer.onFirstRef

void Layer::onFirstRef()
    //surfaceflinger中新建一个BufferQueue
    // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
    mBufferQueue =new SurfaceTextureLayer(mFlinger);
    mSurfaceFlingerConsumer =new SurfaceFlingerConsumer(mBufferQueue, mTextureName);
    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
    mSurfaceFlingerConsumer->setFrameAvailableListener(this);
    mSurfaceFlingerConsumer->setName(mName);
 
    //4.4都是三缓冲
#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
#warning"disabling triple buffering"
    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(2);
#else
    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(3);
#endif
 
    const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
    updateTransformHint(hw);

前面建立好了surfaceControl,下面调用copyFrom

 outSurface.copyFrom(surfaceControl);
    publicvoidcopyFrom(SurfaceControl other) {
        //native中的surfaceControl的指针
        int surfaceControlPtr = other.mNativeObject;
 
        int newNativeObject = nativeCreateFromSurfaceControl(surfaceControlPtr);
 
        synchronized (mLock) {
            if (mNativeObject != 0) {
                nativeRelease(mNativeObject);
            }
            setNativeObjectLocked(newNativeObject);
        }
    }
static jint nativeCreateFromSurfaceControl(JNIEnv* env, jclass clazz,
        jint surfaceControlNativeObj) {
    /*
     * This is used by the WindowManagerService just after constructing
     * a Surface and is necessary for returning the Surface reference to
     * the caller. At this point, we should only have a SurfaceControl.
     */
     //重构一个SurfaceControl
    sp<SurfaceControl> ctrl(reinterpret_cast<SurfaceControl *>(surfaceControlNativeObj));
    //新建一个surface
    sp<Surface> surface(ctrl->getSurface());
    if (surface != NULL) {
        surface->incStrong(&sRefBaseOwner);
    }
    //返回给javasurface的指针
    returnreinterpret_cast<jint>(surface.get());
}
sp<Surface> SurfaceControl::getSurface() const
{
    Mutex::Autolock _l(mLock);
    if (mSurfaceData ==0) {
        // This surface is always consumed by SurfaceFlinger, so the
        // producerControlledByApp value doesn't matter; using false.
        //新建surface,输入参数为BufferQueuecleint
        mSurfaceData =new Surface(mGraphicBufferProducer, false);
    }
    return mSurfaceData;
}
    privatevoidsetNativeObjectLocked(int ptr) {
        if (mNativeObject != ptr) {
            if (mNativeObject == 0 && ptr != 0) {
                mCloseGuard.open("release");
            } elseif (mNativeObject != 0 && ptr == 0) {
                mCloseGuard.close();
            }
            //javasurfacemNativeObject 设置为nativesurface的指针
            mNativeObject = ptr;
            mGenerationId += 1;
        }
    }

上面的outSurface是在WindowManagerService中建立的,分析序列化如何传回给ViewRootImpl

    publicvoidwriteToParcel(Parcel dest, int flags) {
        if (dest == null) {
            thrownew IllegalArgumentException("dest must not be null");
        }
        synchronized (mLock) {
            dest.writeString(mName);
            //写入parcelnativesurface指针
            nativeWriteToParcel(mNativeObject, dest);
        }
        if ((flags & Parcelable.PARCELABLE_WRITE_RETURN_VALUE) != 0) {
            release();
        }
    }
staticvoid nativeWriteToParcel(JNIEnv* env, jclass clazz,
        jint nativeObject, jobject parcelObj) {
    Parcel* parcel = parcelForJavaObject(env, parcelObj);
    if (parcel == NULL) {
        doThrowNPE(env);
        return;
    }
    //重建Surface
    sp<Surface> self(reinterpret_cast<Surface *>(nativeObject));
    //Surface创建时候的BufferQueueclient对象写入到binder
    parcel->writeStrongBinder( self != 0 ? self->getIGraphicBufferProducer()->asBinder() : NULL);
}
sp<IGraphicBufferProducer> Surface::getIGraphicBufferProducer() const {
    return mGraphicBufferProducer;
}

客户端读parcel

 publicstaticfinal Parcelable.Creator<Surface> CREATOR =
            new Parcelable.Creator<Surface>() {
        @Override
        public Surface createFromParcel(Parcel source) {
            try {
                //新建个无参的Surface
                Surface s = new Surface();
                //调用readFromParcel对这个Surface重构
                s.readFromParcel(source);
                return s;
            } catch (Exception e) {
                Log.e(TAG, "Exception creating surface from parcel", e);
                returnnull;
            }
        }
 
        @Override
        public Surface[] newArray(int size) {
            returnnew Surface[size];
        }
    };
publicvoidreadFromParcel(Parcel source) {
        if (source == null) {
            thrownew IllegalArgumentException("source must not be null");
        }
 
        synchronized (mLock) {
            // nativeReadFromParcel() will either return mNativeObject, or
            // create a new native Surface and return it after reducing
            // the reference count on mNativeObject.  Either way, it is
            // not necessary to call nativeRelease() here.
            mName = source.readString();
            //natvicesurface对象的指针设置到java
            setNativeObjectLocked(nativeReadFromParcel(mNativeObject, source));
        }
    }
static jint nativeReadFromParcel(JNIEnv* env, jclass clazz,
        jint nativeObject, jobject parcelObj) {
    Parcel* parcel = parcelForJavaObject(env, parcelObj);
    if (parcel ==NULL) {
        doThrowNPE(env);
        return0;
    }
 
    sp<Surface>self(reinterpret_cast<Surface *>(nativeObject));
    sp<IBinder> binder(parcel->readStrongBinder());
 
    //有可能这个surface已经构造过了,如果IGraphicBufferProducer变化了才会继续走到下面
    // update the Surface only if the underlying IGraphicBufferProducer
    // has changed.
    if (self!=NULL
            && (self->getIGraphicBufferProducer()->asBinder() == binder)) {
        // same IGraphicBufferProducer, return ourselves
        return int(self.get());
    }
 
    sp<Surface> sur;
    //重构BufferQueue的代理对象,即BpGraphicBufferProducer
    sp<IGraphicBufferProducer> gbp(interface_cast<IGraphicBufferProducer>(binder));
    if (gbp !=NULL) {
        // we have a new IGraphicBufferProducer, create a new Surface for it
        //新建Surface
        sur =new Surface(gbp, true);
        // and keep a reference before passing to java
        sur->incStrong(&sRefBaseOwner);
    }
 
    if (self!=NULL) {
        // and loose the java reference to ourselves
        self->decStrong(&sRefBaseOwner);
    }
    //返回给javaSurface的指针
    return int(sur.get());
}

Activity申请Surface过程中,各个类的关系如下图所示,

 

0 0
原创粉丝点击