activity启动

1、Activity.startActivity

public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        // Note we want to go through this call for compatibility with
        // applications that may have overridden the method.
        startActivityForResult(intent, -1);
    }
}

 

 1 public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
 2         @Nullable Bundle options) {
 3     if (mParent == null) {
 4         Instrumentation.ActivityResult ar =
 5             mInstrumentation.execStartActivity(
 6                 this, mMainThread.getApplicationThread(), mToken, this,
 7                 intent, requestCode, options);
 8         if (ar != null) {
 9             mMainThread.sendActivityResult(
10                 mToken, mEmbeddedID, requestCode, ar.getResultCode(),
11                 ar.getResultData());
12         }
13         ...省略
14         cancelInputsAndStartExitTransition(options);
15         // TODO Consider clearing/flushing other event sources and events for child windows.
16     } else {
17         ...省略
18     }
19 }

 2.Instrumentation.execStartActivity

 1 public ActivityResult execStartActivity( 
2
Context who, IBinder contextThread, IBinder token, Activity target, 3 Intent intent, int requestCode, Bundle options) { 4 IApplicationThread whoThread = (IApplicationThread) contextThread; 5 Uri referrer = target != null ? target.onProvideReferrer() : null; 6 if (referrer != null) { 7 intent.putExtra(Intent.EXTRA_REFERRER, referrer); 8 }
       ....
24 try { 25 intent.migrateExtraStreamToClipData(); 26 intent.prepareToLeaveProcess(who); 27 int result = ActivityManagerNative.getDefault() 28 .startActivity(whoThread, who.getBasePackageName(), intent, 29 intent.resolveTypeIfNeeded(who.getContentResolver()), 30 token, target != null ? target.mEmbeddedID : null, 31 requestCode, 0, null, options); 32 checkStartActivityResult(result, intent); 33 } catch (RemoteException e) { 34 throw new RuntimeException("Failure from system", e); 35 } 36 return null; 37 }

3. ActivityManagerNative.getDefault()  返回的是ActivityManagerProxy(是远端传递过来的binder的本地代理,可以理解为客户端的中间者)

 

 

 1    private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
 2         protected IActivityManager create() {
 3             IBinder b = ServiceManager.getService("activity");
 4             if (false) {
 5                 Log.v("ActivityManager", "default service binder = " + b);
 6             }
 7             IActivityManager am = asInterface(b);
 8             if (false) {
 9                 Log.v("ActivityManager", "default service = " + am);
10             }
11             return am;
12         }
13     };
 1 static public IActivityManager asInterface(IBinder obj) {
 2         if (obj == null) {
 3             return null;
 4         }
 5         IActivityManager in =
 6             (IActivityManager)obj.queryLocalInterface(descriptor);
 7         if (in != null) {
 8             return in;
 9         }
10 
11         return new ActivityManagerProxy(obj);
12     }

 

 

4、ActivityManagerProxy

 1     public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
 2             String resolvedType, IBinder resultTo, String resultWho, int requestCode,
 3             int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
 4         Parcel data = Parcel.obtain();
 5         Parcel reply = Parcel.obtain();
 6         data.writeInterfaceToken(IActivityManager.descriptor);
       // caller 就是Activity.startActivity中传递进来的
mMainThread.getApplicationThread()

7      data.writeStrongBinder(caller != null ? caller.asBinder() : null);
 8      data.writeString(callingPackage);  
9
intent.writeToParcel(data, 0);
10 data.writeString(resolvedType);
11 data.writeStrongBinder(resultTo);
12 data.writeString(resultWho);
13 data.writeInt(requestCode);
14 data.writeInt(startFlags);
15 if (profilerInfo != null) {
16 data.writeInt(1);
17 profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
18     } else {
19       data.writeInt(0);
20     }
21     if (options != null) {
22       data.writeInt(1);
23       options.writeToParcel(data, 0);
24     } else {
25       data.writeInt(0);
26     }
//此处调用的是ActivityManagerNative的transact方法
      //mRemote就是远程binder对象,调用transact就会进入stub(ActivityManagerNative)中的onTransact方法
27 mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0); 28 reply.readException(); 29 int result = reply.readInt(); 30 reply.recycle(); 31 data.recycle(); 32 return result; 33 }

5、ActivityManagerNative

@Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case START_ACTIVITY_TRANSACTION:
        {
            data.enforceInterface(IActivityManager.descriptor);
            IBinder b = data.readStrongBinder();
       // b就是Activity.startActivity传递进来的  IApplicationThread app
= ApplicationThreadNative.asInterface(b); String callingPackage = data.readString(); Intent intent = Intent.CREATOR.createFromParcel(data); String resolvedType = data.readString(); IBinder resultTo = data.readStrongBinder(); String resultWho = data.readString(); int requestCode = data.readInt(); int startFlags = data.readInt(); ProfilerInfo profilerInfo = data.readInt() != 0 ? ProfilerInfo.CREATOR.createFromParcel(data) : null; Bundle options = data.readInt() != 0 ? Bundle.CREATOR.createFromParcel(data) : null;
       //调用的是ActivityManagerService的startActivity
int result = startActivity(app, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, options); reply.writeNoException(); reply.writeInt(result); return true; }
     ....

6.ActivityManagerService.startActivity

1 @Override
2     public final int startActivity(IApplicationThread caller, String callingPackage,
3             Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4             int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
5         return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
6                 resultWho, requestCode, startFlags, profilerInfo, bOptions,
7                 UserHandle.getCallingUserId());
8     }

@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
userId, false, ALLOW_FULL_ONLY, "startActivity", null);
// TODO: Switch to user app stacks here.
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null);
}

7. ActivityStarter.startActivityMayWait

final int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, Intent intent, String resolvedType,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int startFlags,
            ProfilerInfo profilerInfo, IActivityManager.WaitResult outResult, Configuration config,
            Bundle bOptions, boolean ignoreTargetSecurity, int userId,
            IActivityContainer iContainer, TaskRecord inTask) {
    ...
int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor,
                    resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                    options, ignoreTargetSecurity, componentSpecified, outRecord, container,
                    inTask);
....    
}   
final int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
            TaskRecord inTask) {
... 省略代码
            doPendingActivityLaunchesLocked(false);
...省略代码
}
final void doPendingActivityLaunchesLocked(boolean doResume) {
        while (!mPendingActivityLaunches.isEmpty()) {
            final PendingActivityLaunch pal = mPendingActivityLaunches.remove(0);
            final boolean resume = doResume && mPendingActivityLaunches.isEmpty();
            try {
                final int result = startActivityUnchecked(
                        pal.r, pal.sourceRecord, null, null, pal.startFlags, resume, null, null);
                postStartActivityUncheckedProcessing(
                        pal.r, result, mSupervisor.mFocusedStack.mStackId, mSourceRecord,
                        mTargetStack);
            } catch (Exception e) {
                Slog.e(TAG, "Exception during pending activity launch pal=" + pal, e);
                pal.sendErrorResult(e.getMessage());
            }
        }
    }
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {
    ......
    if (mDoResume) {
                mSupervisor.resumeFocusedStackTopActivityLocked();
            }
    .....
}  

8.ActivityStackSupervisor.resumeFocusedStackTopActivityLocked

boolean resumeFocusedStackTopActivityLocked(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
        if (targetStack != null && isFocusedStack(targetStack)) {
            return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
        if (r == null || r.state != RESUMED) {
            mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
        }
        return false;
    }

9.ActivityStack.resumeTopActivityUncheckedLocked

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        if (mStackSupervisor.inResumeTopActivity) {
            // Don't even start recursing.
            return false;
        }

        boolean result = false;
        try {
            // Protect against recursion.
            mStackSupervisor.inResumeTopActivity = true;
            if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
                mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
                mService.updateSleepIfNeededLocked();
            }
            result = resumeTopActivityInnerLocked(prev, options);
        } finally {
            mStackSupervisor.inResumeTopActivity = false;
        }
        return result;
    }
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
       ......
      if (mResumedActivity != null) {
    if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
       pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
      }
      ....
         mStackSupervisor.startSpecificActivityLocked(next, true,     true);
      .... }

10.ActivityStack.startPausingLocked

prev.app.thread 是一个ApplicationThread对象的远程接口,通过调用这个远程接口的schedulePauseActivity来通知Launcher进入Paused状态
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,
            boolean dontWait) {
if (prev.app != null && prev.app.thread != null) {
            if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
            try {
                EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
                        prev.userId, System.identityHashCode(prev),
                        prev.shortComponentName);
                mService.updateUsageStats(prev, false);
                prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                        userLeaving, prev.configChangeFlags, dontWait);
            } catch (Exception e) {
                // Ignore exception, if process died other code will cleanup.
                Slog.w(TAG, "Exception thrown during pause", e);
                mPausingActivity = null;
                mLastPausedActivity = null;
                mLastNoHistoryActivity = null;
            }
        } else {
            mPausingActivity = null;
            mLastPausedActivity = null;
            mLastNoHistoryActivity = null;
        }
}

11.ApplicationThreadProxy.schedulePauseActivity

class ApplicationThreadProxy implements IApplicationThread {
    private final IBinder mRemote;

    public ApplicationThreadProxy(IBinder remote) {
        mRemote = remote;
    }

    public final IBinder asBinder() {
        return mRemote;
    }

    public final void schedulePauseActivity(IBinder token, boolean finished,
            boolean userLeaving, int configChanges, boolean dontReport) throws RemoteException {
        Parcel data = Parcel.obtain();
        data.writeInterfaceToken(IApplicationThread.descriptor);
        data.writeStrongBinder(token);
        data.writeInt(finished ? 1 : 0);
        data.writeInt(userLeaving ? 1 :0);
        data.writeInt(configChanges);
        data.writeInt(dontReport ? 1 : 0);
        mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,
                IBinder.FLAG_ONEWAY);
        data.recycle();
    }
}

12.ApplicationThread.schedulePauseActivity

private class ApplicationThread extends ApplicationThreadNative {
        private static final String DB_INFO_FORMAT = "  %8s %8s %14s %14s  %s";

        private int mLastProcessState = -1;

        private void updatePendingConfiguration(Configuration config) {
            synchronized (mResourcesManager) {
                if (mPendingConfiguration == null ||
                        mPendingConfiguration.isOtherSeqNewer(config)) {
                    mPendingConfiguration = config;
                }
            }
        }

        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);
        }
}

ActivityThread中的Handler
case PAUSE_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
SomeArgs args = (SomeArgs) msg.obj;
handlePauseActivity((IBinder) args.arg1, false,
(args.argi1 & USER_LEAVING) != 0, args.argi2,
(args.argi1 & DONT_REPORT) != 0, args.argi3);
maybeSnapshot();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;

13.ActivityThread.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函数来调用Activity.onPause函数,我们知道,在Activity的生命周期中,
        // 当它要让位于其它的Activity时,系统就会调用它的onPause函数
            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) {
                try {
             ActivityManagerNative.getDefault().activityPaused(token); }
catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } mSomeActivitiesChanged = true; } }

 

10.ActivityStackSupervisor.startSpecificActivityLocked

void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);

        r.task.stack.setLaunchTime(r);

        if (app != null && app.thread != null) {
            try {
                if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                        || !"android".equals(r.info.packageName)) {
                    // Don't add this if it is a platform component that is marked
                    // to run in multiple processes, because this is actually
                    // part of the framework so doesn't make sense to track as a
                    // separate apk in the process.
                    app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
                            mService.mProcessStats);
                }
                realStartActivityLocked(r, app, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
        }

        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                "activity", r.intent.getComponent(), false, false, true);
    }

11.ActivityManagerService.startProcessLocked

final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            String hostingType, ComponentName hostingName, boolean allowWhileBooting,
            boolean isolated, boolean keepIfLarge) {
        return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
                hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
                null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
                null /* crashHandler */);
    }

12.

 private final void startProcessLocked(ProcessRecord app, String hostingType,
            String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
 Process.ProcessStartResult startResult = Process.start(entryPoint,
                    app.processName, uid, uid, gids, debugFlags, mountExternal,
                    app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
                    app.info.dataDir, entryPointArgs);
}

 

转载于:https://www.cnblogs.com/zero-66/p/6170653.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值