android小白进阶系列----activity启动分析

前言

曾经我也有迷茫过,android开发过一定经验,我还要干嘛?学其他语言?经过几经思想斗争,我选择了专攻android之路,在我android未达到高层级别,我不会花太多精力去学其他,毕竟android是我饭碗,连饭碗都丢了,还能指望你能学好其他的?那么问题来了怎么专攻?对android底层的了解,无疑对你上层代码使用能更加的 轻车熟路、避免bug。所有才有了源码分析系列的博客
“好记性不如烂笔头”,在看过很多android的FrameWork源码,过几天再回想一下,总是零零散散,不成知识体系,自己动手一步一记录源码分析的过程。同时也给一些想进一步了解android开发一个方向。让我们共同努力。

怎么做

1、工具:android studio
2、双击Shift查找api文件


查找源码文件

3、由外到内的分析,一层一层的解刨

activity启动分析

    //kotlin 语言
    val intent = Intent(this@MainActivity, Main2Activity::class.java)
    this.startActivity(intent)

相信大家对这段代码用得轻车熟路了,我们用它启动一个activity。Ctrl+鼠标左击startActivity。往里面接着看

    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            startActivityForResult(intent, -1);
        }
    }

跳转到了Activity.java的startActivity(Intent intent),细看的有两个重载函数,核心代码在带有两个参数的函数中的startActivityFoResult(Intent intent, int requestCode, @Nullable Bundle options)

  • intent:包含启动activity的信息。
  • requestCode:请求标识字段(略过)
  • options:存储一些启动activity的参数,比如切换动画,一些附带数据等等,详细的可以看ActivityOptions类。常用的我们默认为null。
  public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {//mParent=Activity (1)
            options = transferSpringboardActivityOptions(options);
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }
            cancelInputsAndStartExitTransition(options);
        } else {//activity不为null (2)
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {    
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }

我们先从(2)处开始分析,默认activity不为null。最后都调用startActivityFromChild()。

 public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
            int requestCode, @Nullable Bundle options) {
        //对options进行封装,options为null就采用系统默认
        options = transferSpringboardActivityOptions(options);
        //生成ActivityResult对象,里面包含resultCode和resultData
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, child,
                intent, requestCode, options);
        //执行发送消息ActivityResult
        if (ar != null) {
            mMainThread.sendActivityResult(
                mToken, child.mEmbeddedID, requestCode,
                ar.getResultCode(), ar.getResultData());
        }
        //取消输入功能和动画的执行
        cancelInputsAndStartExitTransition(options);
    }

接下来,我们看下如何生成ActivityResult对象。方法Instrumentation.execStartActivity()

public ActivityResult execStartActivity(                                              
        Context who, IBinder contextThread, IBinder token, Activity target,           
        Intent intent, int requestCode, Bundle options) {                             
    IApplicationThread whoThread = (IApplicationThread) contextThread;                
    Uri referrer = target != null ? target.onProvideReferrer() : null;                
    if (referrer != null) {                                                           
        intent.putExtra(Intent.EXTRA_REFERRER, referrer);                             
    }                                                                                 
    if (mActivityMonitors != null) {                                                  
        synchronized (mSync) {                                                        
            //遍历ActivityMonitor,看是否存在这个Activity                                       
            final int N = mActivityMonitors.size();                                   
            for (int i=0; i= 0 ? am.getResult() : null;              
                    }                                                                 
                    //如果存在就跳出循环                                                       
                    break;                                                            
                }                                                                     
            }                                                                         
        }                                                                             
    }                                                                                 
    try {                                                                             
        intent.migrateExtraStreamToClipData();                                        
        intent.prepareToLeaveProcess(who);                                            
        //真正的startActivity的方法,其实核心功能在whoThread的scheduleLaunchActivity完成的              
          int result = ActivityManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);                
        //用于检查打开Activity异常的方法,比如常见的Activity没在AndroidManifest的话,                       
        // 会抛出“...have you declared this activity in your AndroidManifest.xml?”异常     
        checkStartActivityResult(result, intent);                                     
    } catch (RemoteException e) {                                                     
        throw new RuntimeException("Failure from system", e);                         
    }                                                                                 
    return null;   

ActivityManager.getService().startActivity()方法才是启动activity的核心,内部代码会通过清单文件缓存池中获取对应activity,然后返回result标记,如果没有就会抛出have you declared this activity in your AndroidManifest.xml?”异常 。如果大家有了解过插件化开发原理,滴滴的VirtualApk方法就是从这里入手。通过ActivityManagerProxy 动态代理类,使得将插件化的清单文件缓存进去。首先进去ActivityManager里面看一下getService方法


    /**
     * @hide
     */
    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }
 
    private static final Singleton IActivityManagerSingleton =
            new Singleton() {
                @Override
                protected IActivityManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                    final IActivityManager am = IActivityManager.Stub.asInterface(b);
                    return am;      //ActivityManagerService
                }

这里可能有人找不到对应的startActivity方法在哪里,我这里是有安卓源码通过搜索得到ActivityManagerService中有startActivity并且有addService()

 public void setSystemProcess() {
        try {
            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);

到这里根本的startActivity方法终于找到了,让我们直达内部方法,一看究竟。ActivityManagerService.startActivity方法

  @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());
    }
  @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);
        //这里启动ActivityStarter类中的startActivityMayWait()
        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, bOptions, false, userId, null, null,
                "startActivityAsUser");
    }

startActivityMayWait是个非常长的方法,里面处理的逻辑我们现在可以暂时不看,如何需要查看intent和flags的相关转换时再仔细分析。

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,
            TaskRecord inTask, String reason) {
        //省略
 
            final ActivityRecord[] outRecord = new ActivityRecord[1];
            int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
                    aInfo, rInfo, voiceSession, voiceInteractor,
                    resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                    options, ignoreTargetSecurity, componentSpecified, outRecord, inTask,
                    reason);
 
            Binder.restoreCallingIdentity(origId);
        //省略
       }

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, TaskRecord inTask, String reason) {
        //省略
 
        mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                inTask);
 
        //省略
        return mLastStartActivityResult != START_ABORTED ? mLastStartActivityResult : START_SUCCESS;
    }

这里由于跳转太多,如果一步一步跟进,最后会来到一个ApplicationThread中的scheduleLaunchActivity方法

  @Override
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
                CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
                int procState, Bundle state, PersistableBundle persistentState,
                List pendingResults, List pendingNewIntents,
                boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
 
            updateProcessState(procState, false);
 
            ActivityClientRecord r = new ActivityClientRecord();
 
            r.token = token;
            r.ident = ident;
            r.intent = intent;
            r.referrer = referrer;
            r.voiceInteractor = voiceInteractor;
            r.activityInfo = info;
            r.compatInfo = compatInfo;
            r.state = state;
            r.persistentState = persistentState;
 
            r.pendingResults = pendingResults;
            r.pendingIntents = pendingNewIntents;
 
            r.startsNotResumed = notResumed;
            r.isForward = isForward;
 
            r.profilerInfo = profilerInfo;
 
            r.overrideConfig = overrideConfig;
            updatePendingConfiguration(curConfig);
 
            sendMessage(H.LAUNCH_ACTIVITY, r);
        }

这里发送了一个Handle消息,如果对H.LAUNCH_ACTIVITY进行查找,会来到ActivityThread类中的一段代码

  public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");//见名知意,启动activity
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;

  private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        //省略
 
        Activity a = performLaunchActivity(r, customIntent);
 
        //省略
    }

 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        //调用activity的onCreate()
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                //省略
 
        return activity;
    }

各个类的作用
以下仅供参考

Launcher:用户看到的桌面,只是一个Activity
Instrumentation:在应用代码初始化之前运行,用于监控应用与系统的交互,管理着Application、Activity的生命周期
ActivityManagerService:处于安卓架构的Framework层,运行在SystemServer进程中,调度系统中的所有Activity,AMS会决定哪个Activity可以启动
ActivityStarted:决定了Activity是如何启动的,包含了intent和flags如何被转换并且与任务栈相关联的所有逻辑
ActivityStackSupervisor:Activity的栈管理类
ActivityStack:声明和管理一个activity任务栈的状态
ActivityThread:每一个应用都有对应的ActivityThread,进程创建时会执行ActivityThread的Main方法
ApplicationThread:主要负责与AMS交互

上一张流程图,加深印象


图片来源于网络

你可能感兴趣的:(android小白进阶系列----activity启动分析)