啓動流程從ActivityThread類中的main開始分析如下圖:
對於上圖中一個類中的多個方法是上面的方法調用下面的方法連線是方法調用的另一個方法
下面開始代碼分析(本源碼是android23版本,對於ActivityThread中的main方法是如何調用這裏不做介紹,如想了解,請下載系統源碼查看launcher類,進行分析)
在ActivityThread首先調用main方法
public static void main(String[] args) { ..... Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); ..... throw new RuntimeException("Main thread loop unexpectedly exited"); }
通過代碼可以看到調用了attach方法
private void attach(boolean system) { ..... RuntimeInit.setApplicationObject(mAppThread.asBinder()); final IActivityManager mgr = ActivityManagerNative.getDefault(); try { mgr.attachApplication(mAppThread); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } ...... }
對於上面的ActivityManagerNative.getDefault()上面調用的類實際上是一個代理類,並且用到Singleton<T>單利設計模式代碼如下
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() { protected IActivityManager create() { IBinder b = ServiceManager.getService("activity"); if (false) { Log.v("ActivityManager", "default service binder = " + b); } IActivityManager am = asInterface(b); if (false) { Log.v("ActivityManager", "default service = " + am); } return am; } };
通過gDefault調用get方法獲取 IActivityManager實例類
IBinder b = ServiceManager.getService("activity");這句話獲取的IBinder是ActivityManagerService,通過ActivityManagerService類裏面的
public void setSystemProcess() { try { ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true); ...... } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException( "Unable to find android system package", e); } }對於IActivityManager am = asInterface(b);語句中返回的實體類是ActivityManagerProxy這個類是個代理類(主要實現對ActivityManagerService方法的調用)
mgr.attachApplication(mAppThread);這個語句調用的是ActivityManagerProxy代理類的attachApplication相關代碼如下
//IApplicationThread
public void attachApplication(IApplicationThread app) throws RemoteException
{
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(app.asBinder());
mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);
reply.readException();
data.recycle();
reply.recycle();
}
對於方法中的mRemote指的就是ActivityManagerService這個可以看上面的asInterface方法這個將ams對象傳入進去了,因此這個會調用ActivityManagerService的transact
,對於這個方法它是Binder中的方法因爲這個類繼承Binder方法如下:
/**
* Default implementation rewinds the parcels and calls onTransact. On
* the remote side, transact calls into the binder to do the IPC.
*/
public final boolean transact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
if (false) Log.v("Binder", "Transact: " + code + " to " + this);
if (data != null) {
data.setDataPosition(0);
}
boolean r = onTransact(code, data, reply, flags);
if (reply != null) {
reply.setDataPosition(0);
}
return r;
}
通過方法可以看到調用了onTransact方法因此進入ActivityManagerService類進行查找如下代碼:
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
......
}
try {
return super.onTransact(code, data, reply, flags);
} catch (RuntimeException e) {
// The activity manager only throws security exceptions, so let's
// log all others.
if (!(e instanceof SecurityException)) {
Slog.wtf(TAG, "Activity Manager Crash", e);
}
throw e;
}
}
可以看到調用了父類中的onTransact方法(父類是ActivityManagerNative),在上面的mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0);語句中最終的code應該是
ATTACH_APPLICATION_TRANSACTION因此直接找code值和它相等的值方法如下代碼
case ATTACH_APPLICATION_TRANSACTION: {
data.enforceInterface(IActivityManager.descriptor);
IApplicationThread app = ApplicationThreadNative.asInterface(
data.readStrongBinder());
if (app != null) {
attachApplication(app);
}
reply.writeNoException();
return true;
}
這個地方有調用了attachApplication方法這個方法要去當前類(ActivityManagerService)查找方法代碼如下
@Override
public final void attachApplication(IApplicationThread thread) {
synchronized (this) {
int callingPid = Binder.getCallingPid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid);
Binder.restoreCallingIdentity(origId);
}
}
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid) {
.....
thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,//啓動Application
profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
app.instrumentationUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(mConfiguration), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked());
......
// See if the top visible activity is waiting to run in this process...
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {//啓動activity
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
// Find any services that should be running in this process...
if (!badApp) {
try {
didSomething |= mServices.attachApplicationLocked(app, processName);//啓動服務
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
badApp = true;
}
}
.....
return true;
}
這個地方只分析啓動Appliaction和Activity其中service和activity啓動的差不多不做分析了
thread這個對象對應的類是ActivityThread內部類ApplicationThread調用的方法代碼如下:
public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map<String, IBinder> services, Bundle coreSettings) {
......
sendMessage(H.BIND_APPLICATION, data);//發送了一個message
}
對應的Handler(H)中的調用代碼如下:
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
private void handleBindApplication(AppBindData data) {
.....
try {
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
if (!mInstrumentation.onException(app, e)) {
throw new RuntimeException(
"Unable to create application " + app.getClass().getName()
+ ": " + e.toString(), e);
}
}
} finally {
StrictMode.setThreadPolicy(savedPolicy);
}
}
mInstrumentation對於方法中的這個對象的實體類沒有搞明白是從哪傳過來但是可以直接用Instrumentation進行分析,這個類實現的子類,暫且不用去看,直接看這個類的方法代碼如下:
public void callApplicationOnCreate(Application app) {
app.onCreate();
}
直接調用了Application的onCreate方法這裏對Application的啓動分析到這
下面是Activity的啓動分析接着上面的attachApplicationLocked方法中的mStackSupervisor.attachApplicationLocked(app)語句進行分析
其中mStackSupervisor對象的是ActivityStackSupervisor如下面代碼所示:
public ActivityManagerService(Context systemContext) {
.....
mStackSupervisor = new ActivityStackSupervisor(this);
mActivityStarter = new ActivityStarter(this, mStackSupervisor);
......
}
進入ActivityStackSupervisor類中attachApplicationLocked方法如下: boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
final String processName = app.processName;
boolean didSomething = false;
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = stacks.get(stackNdx);
if (!isFocusedStack(stack)) {
continue;
}
ActivityRecord hr = stack.topRunningActivityLocked();
if (hr != null) {
if (hr.app == null && app.uid == hr.info.applicationInfo.uid
&& processName.equals(hr.processName)) {
try {
if (realStartActivityLocked(hr, app, true, true)) {
didSomething = true;
}
} catch (RemoteException e) {
Slog.w(TAG, "Exception in new application when starting activity "
+ hr.intent.getComponent().flattenToShortString(), e);
throw e;
}
}
}
}
}
if (!didSomething) {
ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}
return didSomething;
}
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
......
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;
}
app.thread這個對象的對應的類是ActivityThread內部類ApplicationThread接下里的就一步步比較簡單了,不做接下來的分析了
接下來的是通過發送Handler消息最終調用handleLaunchActivity方法....
---------------------
以上分析如有不正確的地方,請指出,我們相互學習,我主要是做個筆記,加深一下記憶,謝謝