Activity启动流程

源码为 android 5.0 的源码。 api 21 

android启动的时候,程序的入口是在ActivityThread这个类中,有一个main方法,它是入口函数。


源码:

public static void main(String[] args) {
        SamplingProfilerIntegration.start();
        CloseGuard.setEnabled(false);
        Process.setArgV0("<pre-initialized>");
        Looper.prepareMainLooper();
        if (sMainThreadHandler == null) {
            sMainThreadHandler = new Handler();
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        AsyncTask.init();
        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }


在这个方法中调用prepareMainLooper方法创建一个消息队列。最后进入loop 这是一个死循环 , 消息不停的发送和接收,我们可以在主线程中直接使用handler,而不同创建looper,就是因为源码帮我们做了这个工作 ,如果要在子线程中创建handler,这个时候就需要先创建looper了 。 这里就不分析了。   然后创建ActivityThread对象,在attach方法中,初始化了很多东西。ApplicationThread这个类被初始化。

在attach方法中将当前线程存入到共享线程中。然后调用了一个方法:

	RuntimeInit.setApplicationObject(mAppThread.asBinder());

这里的mAppThread是一个ApplicationThread类对象,传递了一个binder对象,实际上这里的ApplicationThread类继承ApplicationThreadNative类,而这个类继承自Binder类。

	class ApplicationThread extends ApplicationThreadNative

	public abstract class ApplicationThreadNative extends Binder implements IApplicationThread


源代码:

	private void attach(boolean system) {
	    sCurrentActivityThread = this;
	    mSystemThread = system;
		
		if (!system) {
	        IActivityManager mgr = ActivityManagerNative.getDefault();
	        try {
	            mgr.attachApplication(mAppThread);
	        } catch (RemoteException ex) {
	        }
		}
		//...
	}


这里ActivityManagerNative.getDefault()返回的是ActivityManagerService对象。在ActivityManagerService中调用attachApplicationLocked绑定thread

	public final class ActivityManagerService  extends ActivityManagerNative
	        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
			
		public final void attachApplication(IApplicationThread thread) {
	        synchronized (this) {
	            int callingPid = Binder.getCallingPid();
	            final long origId = Binder.clearCallingIdentity();
	            attachApplicationLocked(thread, callingPid);
	            Binder.restoreCallingIdentity(origId);
	        }
	    }
	}

在attachApplicationLocked方法中,比较重要的是:bindApplication和realStartActivityLocked两个方法。

	final boolean realStartActivityLocked(ActivityRecord r,
	            ProcessRecord app, boolean andResume, boolean checkConfig)
	            throws RemoteException {
	
		//冻结其它的app
	    r.startFreezingScreenLocked(app, 0);
		
		//相服务中设置token值,标记
	    mService.mWindowManager.setAppVisibility(r.appToken, true);
		//收集app信息
		r.startLaunchTickingLocked();
		//启动activity
		app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
	        System.identityHashCode(r), r.info,
	        new Configuration(mService.mConfiguration),
	        r.compat, r.icicle, results, newIntents, !andResume,
	        mService.isNextTransitionForward(), profileFile, profileFd,
	        profileAutoStop);
	
	}

realStartActivityLocked方法准备启动actiivity ,调用scheduleLaunchActivity方法,这里app.thread代表的是IApplicationThread thread。ApplicationThreadNative继承IApplicationThread,而ApplicationThread继承ApplicationThreadNative,实际上,调用的是ApplicationThread中的scheduleLaunchActivity方法。

查看在ApplicationThread中的scheduleLaunchActivity方法:

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
                Bundle state, List<ResultInfo> pendingResults,
                List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
                String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
	//创建对象,设置参数
	ActivityClientRecord r = new ActivityClientRecord();
	//...
	//发送消息
	queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
}

queueOrSendMessage方法发送消息出去。

    private void queueOrSendMessage(int what, Object obj) {
        queueOrSendMessage(what, obj, 0, 0);
    }

查看queueOrSendMessage设置消息:

    private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
        synchronized (this) {
            if (DEBUG_MESSAGES) Slog.v(
                TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
                + ": " + arg1 + " / " + obj);
            Message msg = Message.obtain();
            msg.what = what;
            msg.obj = obj;
            msg.arg1 = arg1;
            msg.arg2 = arg2;
            mH.sendMessage(msg);
        }
    }

这里的mh是一个handler的子类:创建的时候就初始化了 final H mH = new H();是一个内部类

	private class H extends Handler {
		//...
	}

在handleMessage中处理消息:

	case LAUNCH_ACTIVITY: {
	    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
	    ActivityClientRecord r = (ActivityClientRecord)msg.obj;
	
	    r.packageInfo = getPackageInfoNoCheck(
	            r.activityInfo.applicationInfo, r.compatInfo);
	    handleLaunchActivity(r, null);
	    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
	} break;

在 handleLaunchActivity方法中调用了performLaunchActivity。

	Activity a = performLaunchActivity(r, customIntent);
而在这个方法中是主要启动activity的方法

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
	
	activity.attach(appContext, this, getInstrumentation(), r.token,
        r.ident, app, r.intent, r.activityInfo, title, r.parent,
        r.embeddedID, r.lastNonConfigurationInstances, config);

	//设置主题
	activity.setTheme(theme);

	//调用oncreate方法
	mInstrumentation.callActivityOnCreate(activity, r.state);
	
	//如果activity没有finish,调用start方法。
	if (!r.activity.mFinished) {
        activity.performStart();
        r.stopped = false;
    }
}

在Instrumentation类中的callActivityOnCreate方法中调用

	activity.performCreate(icicle);

查看activity中的performCreate方法

    final void performCreate(Bundle icicle) {
        onCreate(icicle);
        mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
                com.android.internal.R.styleable.Window_windowNoDisplay, false);
        mFragments.dispatchActivityCreated();
    }

调用onCreate方法。而我们在继承Activity的时候就是继承这个类,然后重写这个onCreate方法,就会调用我们自己的方法。


整个activity就启动了,调用了onCreate方法。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值