Activity启动流程

2018-06-08  本文已影响19人  Joe_blake

Activity启动流程


一、执行startActivity


通过Binder向AMS发送启动Activity请求

二、ActivityManagerService接收启动Activity的请求,并控制前台Activity调用onPause

在AMSstartActivity()方法内部,继续调用startActivityAsUser()方法:

@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}
mIntent.setFlags(mLaunchFlags);//设置启动flag
mReusedActivity = getReusableIntentActivity();//决定是否将新的Activity插入到现有的task
····
final boolean dontStart = top != null && mStartActivity.resultTo == null
                && top.realActivity.equals(mStartActivity.realActivity)
                && top.userId == mStartActivity.userId
                && top.app != null && top.app.thread != null
                && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
                || mLaunchSingleTop || mLaunchSingleTask);
        if (dontStart) {
            ActivityStack.logStartActivity(AM_NEW_INTENT, top, top.task);
            // For paranoia, make sure we have correctly resumed the top activity.
            topStack.mLastPausedActivity = null;
            if (mDoResume) {
                mSupervisor.resumeFocusedStackTopActivityLocked();
            }
          ·····
            return START_DELIVERED_TO_TOP;
        }
·····
mTargetStack.startActivityLocked(mStartActivity, newTask, mKeepCurTransition, mOptions);//启动Activity、是否开启新task···
····
mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);//更新last used stack ID
····

此时,开始进入pause阶段,调用ActivityStack.startPausingLocked()方法,这里截取主要部分:

public final void schedulePauseActivity(IBinder token, boolean finished,
        boolean userLeaving, int configChanges, boolean dontReport) {
    int seq = getLifecycleSeq();
    if (DEBUG_ORDER) Slog.d(TAG, "pauseActivity " + ActivityThread.this
            + " operation received seq: " + seq);
    sendMessage(
            finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
            token,
            (userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),
            configChanges,
            seq);
}

在handleMessage的PAUSE_ACTIVITY/PAUSE_ACTIVITY_FINISHING case中均调用了handlePauseActivity方法:

private void handlePauseActivity(IBinder token, boolean finished,
            boolean userLeaving, int configChanges, boolean dontReport, int seq) {
        ActivityClientRecord r = mActivities.get(token);
        if (DEBUG_ORDER) Slog.d(TAG, "handlePauseActivity " + r + ", seq: " + seq);
        if (!checkAndUpdateLifecycleSeq(seq, r, "pauseActivity")) {
            return;
        }
        if (r != null) {
            //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
            if (userLeaving) {
                performUserLeavingActivity(r);
            }

            r.activity.mConfigChangeFlags |= configChanges;
            performPauseActivity(token, finished, r.isPreHoneycomb(), "handlePauseActivity");

            // Make sure any pending writes are now committed.
            if (r.isPreHoneycomb()) {
                QueuedWork.waitToFinish();
            }

            // Tell the activity manager we have paused.
            if (!dontReport) { //利用ActivityManagerNative通知ActivityThread已经完成pause
                try {
                    ActivityManagerNative.getDefault().activityPaused(token);
                } catch (RemoteException ex) {
                    throw ex.rethrowFromSystemServer();
                }
            }
            mSomeActivitiesChanged = true;
        }
    }

该方法内,调用了performPauseActivityIfNeeded()方法,在该方法中主要执行的是performPauseActivityIfNeeded()方法完成pause,这里我们看一下performPauseActivityIfNeeded方法的具体实现:

private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
    if (r.paused) {
        // You are already paused silly...
        return;
    }

    try {
        r.activity.mCalled = false;
        mInstrumentation.callActivityOnPause(r.activity);
        EventLog.writeEvent(LOG_AM_ON_PAUSE_CALLED, UserHandle.myUserId(),
                r.activity.getComponentName().getClassName(), reason);
        if (!r.activity.mCalled) {
            throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
                    + " did not call through to super.onPause()");
        }
    } catch (SuperNotCalledException e) {
        throw e;
    } catch (Exception e) {
        if (!mInstrumentation.onException(r.activity, e)) {
            throw new RuntimeException("Unable to pause activity "
                    + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
        }
    }
    r.paused = true;
}

该方法中,主要调用了mInstrumentation.callActivityOnPause(r.activity) 来执行目标Activity的onPause方法。前面已经说过,“Instrumentation是启动Activity的操作类”,它的callActivityOnPause()如下,Activity.performPause()方法中我们可以看到的确调用了onPause()方法。

/**
 * Perform calling of an activity's {@link Activity#onPause} method.  The
 * default implementation simply calls through to that method.
 * 
 * @param activity The activity being paused.
 */
public void callActivityOnPause(Activity activity) {
    activity.performPause();
}
final void performPause() {
    mDoReportFullyDrawn = false;
    mFragments.dispatchPause();
    mCalled = false;
    onPause();
    mResumed = false;
    if (!mCalled && getApplicationInfo().targetSdkVersion
            >= android.os.Build.VERSION_CODES.GINGERBREAD) {
        throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onPause()");
    }
    mResumed = false;
}

以上完成了执行onPause的过程,然后在handlePauseActivity()方法中,继续调用ActivityManagerNative.getDefault().activityPaused()方法,向AMS通知onPause过程已完成。

ActivityThread中schedulePauseActivity()发送Message后,处理消息逻辑整理如下:

handlePauseActivity-performPauseActivity-performPauseActivityIfNeeded  //具体执行目标             |                                                             Activity的onpause方法
ActivityManagerNative
        |
        |—>ActivityMangerProxy—>activityPaused    //ActivityMangerProxy通知ActivityThread
                                    |
                                    |—>AMS

ActivityManagerProxy.activityPaused()

public void activityPaused(IBinder token) throws RemoteException
{
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    data.writeInterfaceToken(IActivityManager.descriptor);
    data.writeStrongBinder(token);
    mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0);
    reply.readException();
    data.recycle();
    reply.recycle();
}

ActivityManagerService接收到应用进程创建Activity的请求之后会执行初始化操作,解析启动模式,处理信息等一系列操作。ActivityManagerService保存完请求信息之后会将当前系统栈顶的Activity执行onPause操作。

AMS.activityPaused

@Override
public final void activityPaused(IBinder token) {
    final long origId = Binder.clearCallingIdentity();
    synchronized(this) {
        ActivityStack stack = ActivityRecord.getStackLocked(token);//获取的当前Activity的task的所在栈
        if (stack != null) {
            stack.activityPausedLocked(token, false);
        }
    }
    Binder.restoreCallingIdentity(origId);
}

ActivityStack.activityPausedLocked

if (mPausingActivity == r) {
    if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r
            + (timeout ? " (due to timeout)" : " (pause complete)"));
    completePauseLocked(true, null);
    return;
}

3.任务栈由谁管理,存放在什么地方?

4.启动一个activity都是在主线程中执行的吗?

5.AMS什么时候介入工作的?

6.Binder客户端是怎么和服务端通信的?

7.asinterface含义是什么?

8.整个过程由哪些成员协助完成?

9.他们都起到什么作用?

10.如何图解全过程?

上一篇 下一篇

猜你喜欢

热点阅读