Android系统分析之Activity的启动流程

1 参考链接

Android View系统分析之三Activity的启动与显示–需要进一步分析理解

Android Activity学习笔记——Activity的启动和创建

Android adb你真的会用吗?

2 概念

Activity就是被用来进行与用户交互和用来与android内部特性交互的组件,在应用程序中用到的所有activity都需要在manifest.xml文件中进行注册。那么Activity又是怎样一种组件,怎么样进行显示交互的,一个activity实例是如何被管理和运行起来的,activity生命周期又是怎么一回事?

3 Activity框架和管理结构

AcitivityManagerService是Activity系统服务核心管理类,是一个独立的进程;
ActiveThread是每一个应用程序所在进程的主线程、入口函数,处理循环的消息;
ActiveThread与AcitivityManagerService的通信是属于进程间通信,使用binder机制;
这里写图片描述
(图片来源:Android Activity学习笔记——Activity的启动和创建)

4 Activity启动过程

4.1 启动流程

以启动一个应用程序startActivity为例看一下代码执行的大概流程:
这里写图片描述

可将其分为6个过程:
(1)使用代理模式ActivityManagerNative.ActivityManagerProxy启动到ActivityManagerService中执行;
(2)ActivityStack创建ActivityRecord到历史记录中;
(3)通过Zygote创建ApplicationProcess进程,通过start()启动;
(4)通过ApplicatonThread与ActivityManagerService建立通信;
(5) ActivityManagerService通知ActiveThread启动Activity的创建;
(6)ActivityThread创建Activity加入到mActivities中并开始调度Activity执行;

4.2 详细请看下图

这里写图片描述
这里写图片描述
这里写图片描述

4.3 adnroid系统中四个重要概念:

ActivityManagerService(ActivityManagerNative)系统服务核心管理类,是一个独立的进程;

ActivityStackSupervisor 管理整个手机任务栈;

ActivityStack Activity的栈(任务栈);

PackageManagerService(管理app的包的信息:完成组件在清单里的扫描和注册);

ActivityThread 每一个应用程序所在进程的主线程、入口函数,处理循环的消息。

5 核心源码分析(Android 7.0)

/**
 * Activity
 */
public class Activity {
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);//startActivity()
    }

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

    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        if (mParent == null) {
            Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), ,
                    intent, requestCode, options); //Instrumentation.execStartActivity
        }
    }

}

/**
 * Instrumentation
 */
public class Instrumentation {
    public Instrumentation.ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, android.app.Activity target,
                                                            Intent intent, int requestCode, Bundle options) {
        // ActivityManagerNative.getDefault().startActivity()
        int result = ActivityManagerNative.getDefault().startActivity(whoThread, who.getBasePackageName(), intent, );
        return null;
    }
}

/**
 * ActivityManagerNative
 */
public abstract class ActivityManagerNative extends Binder implements IActivityManager {

    static public IActivityManager getDefault() {
        return gDefault.get();
        //相当于
        IBinder b = ServiceManager.getService("activity");//ActivityManagerNative.getDefault() == ActivityManagerService
        gDefault = asInterface(b);
    }

    public boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
        switch (code) {
            case START_ACTIVITY_TRANSACTION: {
                int result = startActivity(app, callingPackage, intent, resolvedType,
                        resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
                reply.writeInt(result);
                return true;
            }
        }
    }

    public class ActivityManagerProxy implements IActivityManager {
        public int startActivity(IApplicationThread,,,,) { //ActivityManagerService.startActivity
            mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
            return result;
        }
    }
}

/**
 * ActivityManagerService 系统服务核心管理类
 */
public final class ActivityManagerService extends ActivityManagerNative implements BatteryStatsImpl.BatteryCallback {

    public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent,,,,) {
        return startActivityAsUser(caller, callingPackage, intent, , , , ); //startActivityAsUser()
    }

    public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent,,,) {
        return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent, , , );//ActivityStarter.startActivityMayWait()
    }

    //真正启动进程
    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,,,,,,,) {
        return startProcessLocked(processName, info, knownToBeDead, , , , , );//startProcessLocked
    }

    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,,,,,) {
        startProcessLocked();
    }

    startProcessLocked() {
        debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;//linux的Zygote进程

        Process.ProcessStartResult startResult = Process.start(entryPoint, app.processName, , , , , , , );//启动进程:Process.start

        //接着与底层通信
    }
}

//Process
public class Process {
    public static final ProcessStartResult start(final String processClass, final String niceName,,,,,,) {
        return startViaZygote(processClass, niceName, , , , , , , , , ); //开始一个新的进程通过Zygote机制 startViaZygote()
    }
}

/**
 * ActivityStarter
 */
class ActivityStarter {
    final int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage, Intent intent,,,,,,) {
        ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId); //ActivityStackSupervisor.resolveIntent()

        ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);//ActivityStackSupervisor.resolveActivity

        int res = startActivityLocked(caller, intent, ephemeralIntent, , , , , , , ); //ActivityStarter.startActivityLocked()
        return res;
    }

    //验证intent、Class、Permission等;保存将要启动的Activity的Record,例如:记录Activity跳转顺序.
    final int startActivityLocked(IApplicationThread caller, Intent intent,,,,,,) {
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
                intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
                requestCode, componentSpecified, voiceSession != null, mSupervisor, container,
                options, sourceRecord);

        err = startActivityUnchecked(r, sourceRecord, voiceSession, , startFlags, , , inTask);//startActivityUnchecked()
        return err;
    }

    //检查将要启动的Activity的launchMode(启动模式)和启动Flag,根据launcheMode和Flag配置task.
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,, startFlags,, inTask) {
        if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0 || mLaunchSingleInstance || mLaunchSingleTask) {
            final ActivityRecord top = mReusedActivity.task.performClearTaskForReuseLocked(mStartActivity, mLaunchFlags);
            if (top != null) {
                if (top.frontOfTask) {
                    top.task.setIntent(mStartActivity);
                }
                ActivityStack.logStartActivity(AM_NEW_INTENT, mStartActivity, top.task);
                top.deliverNewIntentLocked(mCallingUid, mStartActivity.intent, mStartActivity.launchedFromPackage);
            }
        }

        //任务栈历史栈配置
        mTargetStack.startActivityLocked(mStartActivity, newTask, mKeepCurTransition, mOptions);//ActivityStack.startActivityLocked
    }

}

/**
 * ActivityStackSupervisor 管理整个手机任务栈(ActivityStack)
 */
public final class ActivityStackSupervisor {

    //构造函数
    public ActivityStackSupervisor(ActivityManagerService service) {
        mHandler = new ActivityStackSupervisorHandler(mService.mHandler.getLooper());//ActivityStackSupervisorHandler()
    }

    private final class ActivityStackSupervisorHandler extends Handler {
        void activityIdleInternal(ActivityRecord r) {
            activityIdleInternalLocked(r != null ? r.appToken : null, true, null);//activityIdleInternalLocked()
        }
    }

    final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,) {
        if (activityRemoved) {
            resumeFocusedStackTopActivityLocked();//esumeFocusedStackTopActivityLocked()
        }
    }

    boolean resumeFocusedStackTopActivityLocked() {
        return resumeFocusedStackTopActivityLocked(null, null, null);//resumeFocusedStackTopActivityLocked(,,)
    }

    boolean resumeFocusedStackTopActivityLocked(,,) {
        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);//ActivityStack.resumeTopActivityUncheckedLocked()
        return false;
    }

    ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags, ProfilerInfo profilerInfo, int userId) {
        final ResolveInfo rInfo = resolveIntent(intent, resolvedType, userId);
        return resolveActivity(intent, rInfo, startFlags, profilerInfo);
    }

    ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags) {
        try {
            //AppGlobals
            return AppGlobals.getPackageManager().resolveIntent(intent, , , userId);//PackageManagerService.resolveIntent()
        } catch (RemoteException e) {
        }
        return null;
    }

    //启动进程
    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);

        //真正启动进程 (AMS)ActivityManagerService.startProcessLocked()
        mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false, true);
    }

    boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
        ActivityRecord hr = stack.topRunningActivityLocked();
        if (hr.app == null && app.uid == hr.info.applicationInfo.uid && processName.equals(hr.processName)) {
            if (realStartActivityLocked(hr, app, true, true)) {//realStartActivityLocked()
                didSomething = true;
            }
        }
    }

    final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) {
        app.thread.scheduleLaunchActivity(new Intent(r.intent), , , , , , );//启动activity:ActivityThread.scheduleLaunchActivity()
    }

}

public class AppGlobals {
    public static IPackageManager getPackageManager() { //IPackageManager 实现类似:PackageManagerService
        return ActivityThread.getPackageManager(); //ActivityThread.getPackageManager()
    }
}

/**
 * PackageManagerService 管理app的包的信息:完成组件在清单里的扫描和注册
 */
public class PackageManagerService extends IPackageManager.Stub {
    //初始化时执行
    public static PackageManagerService main(Context context, Installer installer, boolean factoryTest, boolean onlyCore) {
        PackageManagerService m = new PackageManagerService(context, installer, factoryTest, onlyCore);
        ServiceManager.addService("package", m); //ServiceManager添加服务
        return m;
    }

    public ResolveInfo resolveIntent(Intent intent, String resolvedType, int flags, int userId) {
        final ResolveInfo bestChoice = chooseBestActivity(intent, resolvedType, flags, query, userId); //chooseBestActivity()
        return bestChoice;
    }

    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, int flags, List<ResolveInfo> query, int userId) {
        if (query != null) {
            final String intentPackage = intent.getPackage(); //包名
            if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
                ri.resolvePackageName = intentPackage;
                // .....
            }
            return ri;
        }
    }

    public final void attachApplication(IApplicationThread thread) {
        attachApplicationLocked(thread, callingPid);//attachApplicationLocked()
    }

    //附加到Application中
    private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {
        // See if the top visible activity is waiting to run in this process...
        if (normalMode) {
            if (mStackSupervisor.attachApplicationLocked(app)) {//ActivityStackSupervisor.attachApplicationLocked()
                didSomething = true;
            }
        }
        // Find any services that should be running in this process...
        if (!badApp) {
            didSomething |= mServices.attachApplicationLocked(app, processName);
        }
    }
}

/**
 * ActivityThread 安卓java应用层的入口函数类
 */
public final class ActivityThread {
    public static IPackageManager getPackageManager() {
        IBinder b = ServiceManager.getService("package"); //ServiceManager获取服务
        sPackageManager = IPackageManager.Stub.asInterface(b);
        return sPackageManager;
    }

    public static void main(String[] args) {
        Process.setArgV0("<pre-initialized>");
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        thread.attach(false); //attach()
        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }
        if (false) {
            Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        Looper.loop();
    }

    private void attach(boolean system) {
        final IActivityManager mgr = ActivityManagerNative.getDefault();
        mgr.attachApplication(mAppThread); //ActivityManagerService.attachApplication()
    }

    //启动Activity
    public final void scheduleLaunchActivity(Intent intent,,,,) {
        sendMessage(ActivityThread.H.LAUNCH_ACTIVITY, r);//LAUNCH_ACTIVITY
    }

    public void handleMessage(Message msg) {
        case LAUNCH_ACTIVITY: {
            final ActivityThread.ActivityClientRecord r = (ActivityClientRecord) msg.obj;
            r.packageInfo = getPackageInfoNoCheck(r.activityInfo.applicationInfo, r.compatInfo);
            handleLaunchActivity(r, null, "LAUNCH_ACTIVITY"); //handleLaunchActivity()
        }
    }

    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
        Activity a = performLaunchActivity(r, customIntent);//performLaunchActivity()
        if (a != null) {
            handleResumeActivity(r.token, , , , , , );
            if (!r.activity.mFinished && r.startsNotResumed) {
                performPauseActivityIfNeeded(r, reason);
            }
        } else {
            ActivityManagerNative.getDefault().finishActivity(r.token, RESULT_CANCELED, null, , , );
        }
    }

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
        mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
    }
    //Activity启动完成
}

/**
 * ActivityStack Activity的栈(任务栈)
 */
final class ActivityStack {

    //任务栈历史栈配置
    final void startActivityLocked(ActivityRecord r, boolean newTask, boolean keepCurTransition, ActivityOptions options) {
        if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
            insertTaskAtTop(rTask, r);
            mWindowManager.moveTaskToTop(taskId);
        }

        ActivityRecord prev = r.task.topRunningActivityWithStartingWindowLocked();
    }

    //Pause过程暂时不分析

    //确保活动堆栈顶部已恢复, 在ActivityStackSupervisor中调用
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        result = resumeTopActivityInnerLocked(prev, options);//resumeTopActivityInnerLocked()
        return result;
    }

    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
        if (mResumedActivity != null) {
            pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);//查找要进入暂停的Activity
        }
        if (pausing) {
        }
        ActivityStack lastStack = mStackSupervisor.getLastStack();
        //验证该启动的Activity所在进程和app是否存在,若存在,直接启动
        if (next.app != null && next.app.thread != null) {
            mStackSupervisor.startSpecificActivityLocked(next, true, false);//ActivityStackSupervisor.startSpecificActivityLocked()
        } else {//否则,准备创建该进程
            mStackSupervisor.startSpecificActivityLocked(next, true, true);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值