http://blog.csdn.net/lewif/article/details/50735460
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);
privateActivity
performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
Activity activity =
null;
//通过Activity的类名,利用java反射机制来创建对应的Activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
//调用Activity的onCreate函数
mInstrumentation.callActivityOnCreate(activity, r.state);
}
上面主要包括2部分:
1.通过Activity的类名,利用Java反射机制来创建对应的Activity;
2.调用Activity的onCreate函数,进而调用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)
throwsInstantiationException,
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,
newServiceFetcher() {
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;
}
进而调用PhoneWindow的setContentView,
publicvoidsetContentView
(View view) {
setContentView(view,
newViewGroup.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
voidinstallDecor() {
//
This
isthe top-level view
ofthe
window, containing the
windowdecor.
//
private DecorView mDecor;
//m
Decor
是一个
window中最顶层的
view
,包含了
window的装饰
//
①
生成
mDecor
if
(mDecor ==
null) {
mDecor = generateDecor();
}
//
This
isthe view
inwhich the
windowcontents are placed. It
iseither
//
mDecor itself,
ora child
ofmDecor where the contents go.
//m
ContentParent
是放
window中内容的地方,也就是你添加的各种
view
//
它是
DecorView
本身,或者是
DecorView
的
child
//
private ViewGroup mContentParent;
if
(mContentParent ==
null) {
mContentParent = generateLayout(mDecor);
}
}
protected
DecorView
generateDecor() {
//new一个DecorView
returnnew
DecorView(getContext(), -
1);
}
protectedViewGroup
generateLayout(DecorView decor) {
//在DecorView中添加一个view
View
in= mLayoutInflater.inflate(layoutResource,
null);
decor.addView(
in,
newViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
// contentParent 其实就是线程布局,ID_ANDROID_CONTENT
// 而findViewById也是从DecorView中寻找
//所以contentParent是填充在DecorView中的
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
}
public
View
findViewById(
intid) {
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
.LayoutParamsl = 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)
;
}
}
//windowmanagerimpl的addView
publicvoidaddView
(View view, ViewGroup.LayoutParams
params) {
//
mGlobal.addView(view,
params, mDisplay, mParentWindow);
}
//sDefaultWindowManager为static,类数据
publicstatic
WindowManagerGlobal
getInstance() {
synchronized
(WindowManagerGlobal.class) {
if
(sDefaultWindowManager ==
null) {
sDefaultWindowManager =
newWindowManagerGlobal();
}
return
sDefaultWindowManager;
}
}
//windowmanagerglobal的addView
publicvoidaddView
(View view, ViewGroup.LayoutParams
params,
Display display, Window parentWindow) {
ViewRootImpl root;
View panelParentView =
null;
//①新建一个ViewRootImpl,并将其添加到windowmanagerglobal的mRoots
root =
newViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
//private final ArrayList<View> mViews = new ArrayList<View>();
//将参数的view,即mDecor添加到windowmanagerglobal的mViews
mViews.add(view);
//private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();
//windowmanagerglobal的mRoots
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,并将其添加到windowmanagerglobal的mRoots,将mDecor添加到windowmanagerglobal的mViews;
2.将dector添加到root这个ViewRootImpl。
publicViewRootImpl
(Context context, Display display) {
//final IWindowSession mWindowSession;
mWindowSession = WindowManagerGlobal.getWindowSession();
//class W extends IWindow.Stub
//创建一个W ,服务端
mWindow =
newW(
this);
}
ViewRootImpl的构造函数中,主要构建了IWindowSession的代理端,而服务端就是WindowManagerService;创建了一个IWindow的服务端。此外在类ViewRootImpl中有个成员变量为mSurface,调用了无参的Surface构造函数。
privatefinal
Surface mSurface =
newSurface();
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) {
//sWindowManagerService为static
//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 =
newSession(
this, client, inputContext);
return
session;
}
下面分析root.setView(view,wparams, panelParentView);
,既是调用ViewRootImpl的setView(),
/**
* We have one child
*/
publicvoidsetView
(View view, WindowManager.LayoutParams attrs, View panelParentView) {
//①首先mView就是DecorView,只被赋值一次,将DecorView和ViewRootImpl联系
if
(mView ==
null) {
mView = view;
//②调用requestLayout
requestLayout();
//③调用addToDisplay
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mInputChannel);
}
}
首先分析addToDisplay,进而调用Session.addToDisplay(),mWindow为IWindow 的server端,
publicintaddToDisplay
(IWindow window,
intseq, WindowManager.LayoutParams attrs,
int
viewVisibility,
intdisplayId, Rect outContentInsets,
InputChannel outInputChannel) {
return
mService.addWindow(
this, window, seq, attrs, viewVisibility, displayId,
outContentInsets, outInputChannel);
}
—>WindowManagerService.addWindow(),
//WindowManagerService中为IWindow的client端
publicint
addWindow(Session session, IWindow
client,
intseq,
WindowManager.LayoutParams attrs,
intviewVisibility,
intdisplayId,
Rect outContentInsets, InputChannel outInputChannel) {
//创建一个WindowState
win =
newWindowState(
this, session,
client, token,
attachedWindow, appOp[
0], seq, attrs, viewVisibility, displayContent);
//调用WindowState的attach
win.attach();
// final HashMap<IBinder, WindowState> mWindowMap = new HashMap<IBinder, WindowState>();
// HashMap,IWindow的代理和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 =
newSurfaceSession();
//将mSession保存到WindowManagerService的mSessions
mService.mSessions.add(
this);
}
mNumWindow++;
}
SurfaceComposerClient专门用来和surface flinger建立connection(ISurfaceComposerClient),SurfaceComposerClient是client,而surface flinger中的server为Client,SurfaceSession就是SurfaceComposerClient在java层的代表,其mNativeClient成员就是native层的SurfaceComposerClient对象的指针。
/** Create a new connection with the surface flinger. */
publicSurfaceSession
() {
mNativeClient = nativeCreate();
}
static jint nativeCreate(JNIEnv* env, jclass clazz) {
SurfaceComposerClient* client =
newSurfaceComposerClient();
client->incStrong((
void*)nativeCreate);
returnreinterpret_cast
<jint>(client);
}
SurfaceComposerClient
::SurfaceComposerClient()
: mStatus(NO_INIT), mComposer(Composer
::getInstance())
{
}
voidSurfaceComposerClient
::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(
newClient(
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其实主要是对应native的Surface对象,有了surface就能dequeue buffer了,然后再去画图啥的。
privateintrelayoutWindow
(WindowManager.LayoutParams
params,
intviewVisibility,
boolean insetsPending) throws RemoteException {
//binder,调用Session的relayout,返回填充的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);
}
利用IWindowSession和Session通信,调用relayout,注意,这里mSurface是ViewRootImpl的成员变量,开始调用了无参的构造函数,IWindowSession.aidl文件中,mSurface是被out修饰,因此是在server端创建,然后再binder返回给ViewRootImpl。
Session—>relayout(),
publicintrelayout
(IWindow window,
intseq, WindowManager.LayoutParams attrs,
int
requestedWidth,
intrequestedHeight,
intviewFlags,
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,
intseq,
WindowManager.LayoutParams attrs,
intrequestedWidth,
int
requestedHeight,
intviewVisibility,
intflags,
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,
intw,
inth,
intformat,
intflags)
throws
OutOfResourcesException {
//session就是SurfaceComposerClient在java层的代表
//mNativeObject是native层SurfaceControl的指针
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);
//返回给java层SurfaceControl的指针
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就是surfacefligner中Layer的mBufferQueue的client端(IGraphicBufferProducer)
if
(err
==NO_ERROR) {
sur
=newSurfaceControl(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就是surfacefligner中Layer的mBufferQueue的client端
*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 :
publicMessageBase {
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{
returnresult; }
virtualbool
handler() {
result = flinger->createLayer(name, client, w, h, format, flags,
handle, gbp);
returntrue
;
}
};
sp<MessageBase> msg =
newMessageCreateLayer(mFlinger.
get(),
name,
this, w, h, format, flags, handle, gbp);
mFlinger->postMessageSync(msg);
return
static_cast<MessageCreateLayer*>( msg.
get() )->getResult();
}
进而调用flinger.createLayer()—>Layer.onFirstRef
voidLayer
::onFirstRef()
{
//surfaceflinger中新建一个BufferQueue
// Creates a custom BufferQueue for SurfaceFlingerConsumer to use
mBufferQueue
=newSurfaceTextureLayer(mFlinger);
mSurfaceFlingerConsumer
=newSurfaceFlingerConsumer(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);
}
//返回给java层surface的指针
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,输入参数为BufferQueue的cleint端
mSurfaceData
=newSurface(mGraphicBufferProducer,
false);
}
return
mSurfaceData;
}
privatevoidsetNativeObjectLocked
(
intptr) {
if
(mNativeObject != ptr) {
if
(mNativeObject ==
0&& ptr !=
0) {
mCloseGuard.open(
"release");
}
elseif(mNativeObject !=
0&& ptr ==
0) {
mCloseGuard.close();
}
//将java层surface的mNativeObject 设置为native层surface的指针
mNativeObject = ptr;
mGenerationId +=
1;
}
}
上面的outSurface是在WindowManagerService中建立的,分析序列化如何传回给ViewRootImpl,
publicvoidwriteToParcel
(Parcel dest,
intflags) {
if
(dest ==
null) {
thrownew
IllegalArgumentException(
"dest must not be null");
}
synchronized
(mLock) {
dest.writeString(mName);
//写入parcel,native层surface指针
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创建时候的BufferQueue的client对象写入到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 =
newSurface();
//调用readFromParcel对这个Surface重构
s.readFromParcel(source);
return
s;
}
catch(Exception e) {
Log.e(TAG,
"Exception creating surface from parcel", e);
returnnull
;
}
}
@Override
public
Surface[]
newArray(
intsize) {
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();
//将natvice的surface对象的指针设置到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
=newSurface(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);
}
//返回给java层Surface的指针
return
int(sur
.get());
}
Activity申请Surface过程中,各个类的关系如下图所示,