美文网首页framwork
android Framework——Launch Activi

android Framework——Launch Activi

作者: Peakmain | 来源:发表于2021-04-29 11:43 被阅读0次

    一、Launch Activity请求AMS过程

    无论是点击桌面图标调用 startActivitySafely 还是直接调用 startActivity 在源码中都是调用的 startActivityForResult 方法

        public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
                @Nullable Bundle options) {
       //mParent 实际是activity表示当前Activity的父类,此时第一次进来肯定为空
            if (mParent == null) {
                options = transferSpringboardActivityOptions(options);
                Instrumentation.ActivityResult ar =
                    mInstrumentation.execStartActivity(
                        this, mMainThread.getApplicationThread(), mToken, this,
                        intent, requestCode, options);
            } else {
           
            }
        }
        public ActivityResult execStartActivity(
                Context who, IBinder contextThread, IBinder token, Activity target,
                Intent intent, int requestCode, Bundle options) {
         ....
            try {
                intent.migrateExtraStreamToClipData();
                intent.prepareToLeaveProcess(who);
                int result = ActivityManager.getService()
                    .startActivity(whoThread, who.getBasePackageName(), intent,
                            intent.resolveTypeIfNeeded(who.getContentResolver()),
                            token, target != null ? target.mEmbeddedID : null,
                            requestCode, 0, null, options);
                checkStartActivityResult(result, intent);
            } catch (RemoteException e) {
                throw new RuntimeException("Failure from system", e);
            }
            return null;
        }
    

    首先会调用ActivityManager的getService来获取AMS的代理对象,然后调用startActivity方法

        public static IActivityManager getService() {
            return IActivityManagerSingleton.get();
        }
        private static final Singleton<IActivityManager> IActivityManagerSingleton =
                new Singleton<IActivityManager>() {
                    @Override
                    protected IActivityManager create() {
                    //获取到IBinder的AMS的引用
                        final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                        //IBinder转成IActivityManager类型的对象
                        final IActivityManager am = IActivityManager.Stub.asInterface(b);
                        return am;
                    }
                };
    

    上面代码我们可以看到采用的实际是AIDL形式,IActivityManager.java是由AIDL工具在编译时自动生成得到的。要实现进程间通信,服务端也就是AMS只需要继承IActivityManager.stub类实现。
    由上面的代码我们可以知道,Instrumentation类的execStartActivity最终是实际调用的是AMS的startActivity


    image.png

    AMS到ApplicationThread的调用过程

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

    startActivityAsUser比startActivity多了一个参数UserHandle.getCallingUserId(),这个参数用于确定调用者的权限

        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) {
            return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                    resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                    true /*validateIncomingUser*/);
        }
        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,
                boolean validateIncomingUser) {
              //判断进程是否需要被隔离,若被隔离则会抛出异常
            enforceNotIsolatedCaller("startActivity");
             
            userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
                    Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    
            return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
                    .setCaller(caller)
                    .setCallingPackage(callingPackage)
                    .setResolvedType(resolvedType)
                    .setResultTo(resultTo)
                    .setResultWho(resultWho)
                    .setRequestCode(requestCode)
                    .setStartFlags(startFlags)
                    .setProfilerInfo(profilerInfo)
                    .setActivityOptions(bOptions)
                    .setMayWait(userId)
                    .execute();
    
        }
     int execute() {
            try {
      
                if (mRequest.mayWait) {
                    return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                            mRequest.callingPackage, mRequest.intent, mRequest.resolvedType,
                            mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                            mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                            mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                            mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                            mRequest.inTask, mRequest.reason,
                            mRequest.allowPendingRemoteAnimationRegistryLookup);
                } else {
                }
            } finally {
                onExecutionComplete();
            }
        }
    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, WaitResult outResult,
                Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
                IActivityContainer iContainer, TaskRecord inTask, String reason) {
             ...
            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, reason);
             ...
             return res;
         }
     }
        private int startActivity(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,
                SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
                ActivityRecord[] outActivity, TaskRecord inTask, String reason,
                boolean allowPendingRemoteAnimationRegistryLookup) {
    
            mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                    callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                    options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                    inTask, allowPendingRemoteAnimationRegistryLookup);
            return getExternalResult(mLastStartActivityResult);
        }
    
        private int startActivity(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,
                SafeActivityOptions options,
                boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
                TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
            int err = ActivityManager.START_SUCCESS;
         
            final Bundle verificationBundle
                    = options != null ? options.popAppVerificationBundle() : null;
            ProcessRecord callerApp = null;
            if (caller != null) {
           //获取Launcher进程
                callerApp = mService.getRecordForAppLocked(caller);
                if (callerApp != null) {
                   //.\获取pid和uid
                    callingPid = callerApp.pid;
                    callingUid = callerApp.info.uid;
                } else {
                    err = ActivityManager.START_PERMISSION_DENIED;
                }
             //创建ActivityRecord ,用于描述即将 启动的Activity
            ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                    callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
                    resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
                    mSupervisor, checkedOptions, sourceRecord);
            if (outActivity != null) {
          //将ActivityRecord 赋值给ActivityRecord[]类型的outActivity
                outActivity[0] = r;
            }
            mController.doPendingActivityLaunches(false);
          
            return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                    true /* doResume */, checkedOptions, inTask, outActivity);
        }
        private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                    IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                    int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                    ActivityRecord[] outActivity) {
            int result = START_CANCELED;
            try {
                mService.mWindowManager.deferSurfaceLayout();
                result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                        startFlags, doResume, options, inTask, outActivity);
            }
            postStartActivityProcessing(r, result, mTargetStack);
    
            return result;
        }
      private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity) {
    ...
     if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
                    && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {//1
                newTask = true;
                //创建新的TaskRecord
                result = setTaskFromReuseOrCreateNewTask(
                        taskToAffiliate, preferredLaunchStackId, topStack);//2
            } else if (mSourceRecord != null) {
                result = setTaskFromSourceRecord();
            } else if (mInTask != null) {
                result = setTaskFromInTask();
            } else {
                setTaskToCurrentTopOrCreateNewTask();
            }
           ...
     if (mDoResume) {
                final ActivityRecord topTaskActivity =
                        mStartActivity.getTask().topRunningActivityLocked();
                if (!mTargetStack.isFocusable()
                        || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                        && mStartActivity != topTaskActivity)) {
                   ...
                } else {
                    if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                        mTargetStack.moveToFront("startActivityUnchecked");
                    }
                    mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                            mOptions);//3
                }
            } else {
                mTargetStack.addRecentActivityLocked(mStartActivity);
            }
            ...
    }
        boolean resumeFocusedStackTopActivityLocked(
                ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    
            if (!readyToResume()) {
                return false;
            }
    
            if (targetStack != null && isFocusedStack(targetStack)) {
                return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
            }
           //获取要启动的activity所在栈顶并且不处于停止状态的ActivityRecord
            final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
            if (r == null || !r.isState(RESUMED)) {
                mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
            } else if (r.isState(RESUMED)) {
                // Kick off any lingering app transitions form the MoveTaskToFront operation.
                mFocusedStack.executeAppTransition(targetOptions);
            }
    
            return false;
        }
        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;
                result = resumeTopActivityInnerLocked(prev, options);
                final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
                if (next == null || !next.canTurnScreenOn()) {
                    checkReadyForSleep();
                }
            } finally {
                mStackSupervisor.inResumeTopActivity = false;
            }
    
            return result;
        }
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
          ...
               mStackSupervisor.startSpecificActivityLocked(next, true, true);
           }
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
           return true;
    }
    
        void startSpecificActivityLocked(ActivityRecord r,
                boolean andResume, boolean checkConfig) {
            // activity所在应用的进程
            ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                    r.info.applicationInfo.uid, true);
    
            getLaunchTimeTracker().setLaunchTime(r);
    
            if (app != null && app.thread != null) {
                 //app所在应用程序进程已经运行
            try {
                   if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                           || !"android".equals(r.info.packageName)) {
                       app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
                               mService.mProcessStats);
                   }
                   realStartActivityLocked(r, app, andResume, checkConfig);//3
                   return;
               } catch (RemoteException e) {
                   Slog.w(TAG, "Exception when starting activity "
                           + r.intent.getComponent().flattenToShortString(), e);
               }
            }
           // 当前进程没有创建则先创建进程
            mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
                    "activity", r.intent.getComponent(), false, false, true);
        }
      final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
              boolean andResume, boolean checkConfig) throws RemoteException {
       ...
          //app.thred实际是IApplicationThread,实现是ActivityThread的内部类ApplicationThread.而且实现IActivityManager.stub类
              app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                      System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                      new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
                      task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
                      newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
      ...      
          return true;
      }
    
    image.png
    image.png

    相关文章

      网友评论

        本文标题:android Framework——Launch Activi

        本文链接:https://www.haomeiwen.com/subject/suvirltx.html