Android加载流程解析(从app启动到执行onCreate)

Android软件的主入口也是main,这个main方法定义在ActivityThread中:

public static void main(String[] args) {
    
    
    ...
    Looper.prepareMainLooper();

    ActivityThread thread = new ActivityThread();
    thread.attach(false);

    if (sMainThreadHandler == null) {
    
    
        sMainThreadHandler = thread.getHandler();
    }
	...
        
    Looper.loop();
	...
}

这里主要用到了Handler机制,由于本文主要讲述Android加载机制,所有不过多分析Handlermain方法中主要有一个Looper,一直在循环等待消息(Message),main方法中大多数都是主线程Handler的一些操作,除此之外最重要的就是:

thread.attach(false);

查看attach方法

private void attach(boolean system) {
    
    
    ...
    final IActivityManager mgr = ActivityManager.getService(); //1
    try {
    
    
        mgr.attachApplication(mAppThread);  //2
    } catch (RemoteException ex) {
    
    
        throw ex.rethrowFromSystemServer();
    }
    ...
}

1处获得了IActivityManager对象mgr,该对象是系统通过Binder机制创建的,是Activity的管理类,该类由系统服务所调用管理,并且通过在binder接口当中进行调用。

2处的ApplicationThread对象mAppThreadActivityThread的成员变量,该类也是ActivityThread的内部类

private class ApplicationThread extends IApplicationThread.Stub {
    
    
    public final void scheduleResumeActivity(IBinder token, int processState,
    boolean isForward, Bundle resumeArgs) {
    
    
		...
        sendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0, 0, seq);
    }

    // we use token to identify this activity without having to send the
    // activity itself back to the activity manager. (matters more with ipc)
    @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<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
    boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
    
    
		...
        sendMessage(H.LAUNCH_ACTIVITY, r);
    }
    ...
}

也就是说mgr与操作系统(由系统服务调用)有关,而ApplicationThread只是ActivityThread的内部类,因此调用mgrattachApplication让android应用建立起与操作系统的关系,操作系统在收到对应的事件后,通过ApplicationThread的方法向app发送系统信息。例如当用户打开app的时候,系统会通过mgr间接调用scheduleLaunchActivity,该方法向主线程Handler发送信息:

sendMessage(H.LAUNCH_ACTIVITY, r);

查看HandlerhandlerMessage方法

public void handleMessage(Message msg) {
    
    
    ...
    switch (msg.what) {
    
    
        case LAUNCH_ACTIVITY: {
    
    
            ...
            final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
            handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
        } break;
        ...
    }
}

ActivityClientRecord的对象保存了系统传过来的参数,查看handleLaunchActivity

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
    
    
    Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
    
    
    	...
        handleResumeActivity(r.token, false, r.isForward,
            !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
        ...
    }
    ...
}

该方法主要执行Activity的加载(Launch)或者Resume工作,继续查看performLaunchActivity

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    
    
    ...
    try {
    
    
		...
        if (activity != null) {
    
    
            ...
            if (r.isPersistable()) {
    
    
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
    
    
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
        }
    }
    return activity;     
}	

查看mInstrumentation对象的callActivityOnCreate方法

public void callActivityOnCreate(Activity activity, Bundle icicle,
	PersistableBundle persistentState) {
    
    
	prePerformCreate(activity);
	activity.performCreate(icicle, persistentState);
	postPerformCreate(activity);
}

从上面三个方法名来看,该方法主要做了ActivityCreate,已经Create的前后(pre和post)工作,查看performCreate方法

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    
    
	...
    if (persistentState != null) {
    
    
        onCreate(icicle, persistentState);
    } else {
    
    
        onCreate(icicle);
    }
    ...
}

到这就恍然大悟了,Handler在接收到对应信息(Message)后执行操作,最后会调用ActivityonCreate方法,至此完成了ActivityLaunch过程。

猜你喜欢

转载自blog.csdn.net/weixin_48968045/article/details/114499320