前言
在Android系統(tǒng)中伐弹,Activity和Service是應用程序的核心組件署惯,它們以松藕合的方式組合在一起構(gòu)成了一個完整的應用程序双抽,這得益于應用程序框架層提供了一套完整的機制來協(xié)助應用程序啟動這些Activity和Service模孩,以及提供Binder機制幫助它們相互間進行通信。
在Android系統(tǒng)中恢共,有兩種操作會引發(fā)Activity的啟動,一種用戶點擊應用程序圖標時召锈,Launcher會為我們啟動應用程序的主Activity旁振;應用程序的默認Activity啟動起來后,它又可以在內(nèi)部通過調(diào)用startActvity接口啟動新的Activity涨岁,依此類推拐袜,每一個Activity都可以在內(nèi)部啟動新的Activity瞬项。通過這種連鎖反應摄狱,按需啟動Activity裸卫,從而完成應用程序的功能蛔钙。
這里绊含,我們通過一個具體的例子來說明如何啟動Android應用程序的Activity针肥。Activity的啟動方式有兩種秦叛,一種是顯式的阱持,一種是隱式的琐馆,隱式啟動可以使得Activity之間的藕合性更加松散规阀,因此,這里只關注隱式啟動Activity的方法瘦麸。
- MainActivity的啟動過程如下圖所示:.
簡要流程
① 點擊桌面App圖標谁撼,Launcher進程采用Binder IPC向system_server進程發(fā)起startActivity請求;
② system_server進程接收到請求后滋饲,向zygote進程發(fā)送創(chuàng)建進程的請求厉碟;
③ Zygote進程fork出新的子進程,即App進程屠缭;
④ App進程箍鼓,通過Binder IPC向sytem_server進程發(fā)起attachApplication請求;
⑤ system_server進程在收到請求后呵曹,進行一系列準備工作后款咖,再通過binder IPC向App進程發(fā)送scheduleLaunchActivity請求;
⑥ App進程的binder線程(ApplicationThread)在收到請求后奄喂,通過handler向主線程發(fā)送LAUNCH_ACTIVITY消息之剧;
⑦ 主線程在收到Message后,通過發(fā)射機制創(chuàng)建目標Activity砍聊,并回調(diào)Activity.onCreate()等方法背稼。
⑧ 到此,App便正式啟動玻蝌,開始進入Activity生命周期蟹肘,執(zhí)行完onCreate/onStart/onResume方法词疼,UI渲染結(jié)束后便可以看到App的主界面。
具體流程
Step 1. Launcher.startActivitySafely
在Android系統(tǒng)中帘腹,應用程序是由Launcher啟動起來的贰盗,其實,Launcher本身也是一個應用程序阳欲,其它的應用程序安裝后舵盈,就會Launcher的界面上出現(xiàn)一個相應的圖標,點擊這個圖標時球化,Launcher就會對應的應用程序啟動起來秽晚。
Launcher的源代碼工程在packages/apps/Launcher2目錄下,負責啟動其它應用程序的源代碼實現(xiàn)在src/com/android/launcher2/Launcher.java文件中:
/**
* Default launcher application.
*/
public final class Launcher extends Activity
implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, AllAppsView.Watcher {
......
/**
* Launches the intent referred by the clicked shortcut.
*
* @param v The view representing the clicked shortcut.
*/
public void onClick(View v) {
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
// Open shortcut
final Intent intent = ((ShortcutInfo) tag).intent;
int[] pos = new int[2];
v.getLocationOnScreen(pos);
intent.setSourceBounds(new Rect(pos[0], pos[1],
pos[0] + v.getWidth(), pos[1] + v.getHeight()));
startActivitySafely(intent, tag);
} else if (tag instanceof FolderInfo) {
......
} else if (v == mHandleView) {
......
}
}
void startActivitySafely(Intent intent, Object tag) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
......
} catch (SecurityException e) {
......
}
}
......
}
它的默認Activity是MainActivity筒愚,這里是AndroidManifest.xml文件中配置的:
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
因此赴蝇,這里的intent包含的信息為:action = "android.intent.action.Main",category="android.intent.category.LAUNCHER", cmp="shy.luo.activity/.MainActivity"巢掺,表示它要啟動的Activity為shy.luo.activity.MainActivity句伶。Intent.FLAG_ACTIVITY_NEW_TASK表示要在一個新的Task中啟動這個Activity,注意陆淀,Task是Android系統(tǒng)中的概念考余,它不同于進程Process的概念。簡單地說轧苫,一個Task是一系列Activity的集合楚堤,這個集合是以堆棧的形式來組織的,遵循后進先出的原則浸剩。事實上钾军,Task是一個非常復雜的概念鳄袍,有興趣的讀者可以到官網(wǎng)查看相關的資料绢要。這里,我們只要知道拗小,這個MainActivity要在一個新的Task中啟動就可以了重罪。
Step 2. Activity.startActivity
在Step 1中,我們看到哀九,Launcher繼承于Activity類剿配,而Activity類實現(xiàn)了startActivity函數(shù),因此阅束,這里就調(diào)用了Activity.startActivity函數(shù)呼胚,它實現(xiàn)在frameworks/base/core/java/android/app/Activity.java文件中:
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks {
......
@Override
public void startActivity(Intent intent) {
startActivityForResult(intent, -1);
}
......
}
這個函數(shù)實現(xiàn)很簡單,它調(diào)用startActivityForResult來進一步處理息裸,第二個參數(shù)傳入-1表示不需要這個Actvity結(jié)束后的返回結(jié)果蝇更。
Step 3. Activity.startActivityForResult
這個函數(shù)也是實現(xiàn)在frameworks/base/core/java/android/app/Activity.java文件中:
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks {
......
public void startActivityForResult(Intent intent, int requestCode) {
if (mParent == null) {
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode);
......
} else {
......
}
......
}
這里的mInstrumentation是Activity類的成員變量沪编,它的類型是Intrumentation,定義在frameworks/base/core/java/android/app/Instrumentation.java文件中年扩,它用來監(jiān)控應用程序和系統(tǒng)的交互蚁廓。
這里的mMainThread也是Activity類的成員變量,它的類型是ActivityThread厨幻,它代表的是應用程序的主線程相嵌。這里通過mMainThread.getApplicationThread獲得它里面的ApplicationThread成員變量,它是一個Binder對象况脆,后面我們會看到饭宾,ActivityManagerService會使用它來和ActivityThread來進行進程間通信。這里我們需注意的是漠另,這里的mMainThread代表的是Launcher應用程序運行的進程捏雌。
這里的mToken也是Activity類的成員變量,它是一個Binder對象的遠程接口笆搓。
Step 4. Instrumentation.execStartActivity
這個函數(shù)定義在frameworks/base/core/java/android/app/Instrumentation.java文件中:
public class Instrumentation {
......
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
if (mActivityMonitors != null) {
......
}
try {
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
null, 0, token, target != null ? target.mEmbeddedID : null,
requestCode, false, false);
......
} catch (RemoteException e) {
}
return null;
}
......
}
這里的ActivityManagerNative.getDefault返回ActivityManagerService的遠程接口性湿,即ActivityManagerProxy接口。
這里的intent.resolveTypeIfNeeded返回這個intent的MIME類型满败,在這個例子中肤频,沒有AndroidManifest.xml設置MainActivity的MIME類型,因此算墨,這里返回null宵荒。
這里的target不為null,但是target.mEmbddedID為null净嘀,我們不用關注报咳。
Step 5. ActivityManagerProxy.startActivity
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:
class ActivityManagerProxy implements IActivityManager
{
......
public int startActivity(IApplicationThread caller, Intent intent,
String resolvedType, Uri[] grantedUriPermissions, int grantedMode,
IBinder resultTo, String resultWho,
int requestCode, boolean onlyIfNeeded,
boolean debug) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(caller != null ? caller.asBinder() : null);
intent.writeToParcel(data, 0);
data.writeString(resolvedType);
data.writeTypedArray(grantedUriPermissions, 0);
data.writeInt(grantedMode);
data.writeStrongBinder(resultTo);
data.writeString(resultWho);
data.writeInt(requestCode);
data.writeInt(onlyIfNeeded ? 1 : 0);
data.writeInt(debug ? 1 : 0);
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
reply.readException();
int result = reply.readInt();
reply.recycle();
data.recycle();
return result;
}
......
}
這里的參數(shù)比較多,我們先整理一下挖藏。從上面的調(diào)用可以知道暑刃,這里的參數(shù)resolvedType、grantedUriPermissions和resultWho均為null膜眠;參數(shù)caller為ApplicationThread類型的Binder實體岩臣;參數(shù)resultTo為一個Binder實體的遠程接口,我們先不關注它宵膨;參數(shù)grantedMode為0架谎,我們也先不關注它;參數(shù)requestCode為-1辟躏;參數(shù)onlyIfNeeded和debug均空false谷扣。
Step 6. ActivityManagerService.startActivity
上一步Step 5通過Binder驅(qū)動程序就進入到ActivityManagerService的startActivity函數(shù)來了,它定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
public final int startActivity(IApplicationThread caller,
Intent intent, String resolvedType, Uri[] grantedUriPermissions,
int grantedMode, IBinder resultTo,
String resultWho, int requestCode, boolean onlyIfNeeded,
boolean debug) {
return mMainStack.startActivityMayWait(caller, intent, resolvedType,
grantedUriPermissions, grantedMode, resultTo, resultWho,
requestCode, onlyIfNeeded, debug, null, null);
}
......
}
這里只是簡單地將操作轉(zhuǎn)發(fā)給成員變量mMainStack的startActivityMayWait函數(shù)捎琐,這里的mMainStack的類型為ActivityStack会涎。
Step 7. ActivityStack.startActivityMayWait
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
final int startActivityMayWait(IApplicationThread caller,
Intent intent, String resolvedType, Uri[] grantedUriPermissions,
int grantedMode, IBinder resultTo,
String resultWho, int requestCode, boolean onlyIfNeeded,
boolean debug, WaitResult outResult, Configuration config) {
......
boolean componentSpecified = intent.getComponent() != null;
// Don't modify the client's object!
intent = new Intent(intent);
// Collect information about the target of the Intent.
ActivityInfo aInfo;
try {
ResolveInfo rInfo =
AppGlobals.getPackageManager().resolveIntent(
intent, resolvedType,
PackageManager.MATCH_DEFAULT_ONLY
| ActivityManagerService.STOCK_PM_FLAGS);
aInfo = rInfo != null ? rInfo.activityInfo : null;
} catch (RemoteException e) {
......
}
if (aInfo != null) {
// Store the found target back into the intent, because now that
// we have it we never want to do this again. For example, if the
// user navigates back to this point in the history, we should
// always restart the exact same activity.
intent.setComponent(new ComponentName(
aInfo.applicationInfo.packageName, aInfo.name));
......
}
synchronized (mService) {
int callingPid;
int callingUid;
if (caller == null) {
......
} else {
callingPid = callingUid = -1;
}
mConfigWillChange = config != null
&& mService.mConfiguration.diff(config) != 0;
......
if (mMainStack && aInfo != null &&
(aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
......
}
int res = startActivityLocked(caller, intent, resolvedType,
grantedUriPermissions, grantedMode, aInfo,
resultTo, resultWho, requestCode, callingPid, callingUid,
onlyIfNeeded, componentSpecified);
if (mConfigWillChange && mMainStack) {
......
}
......
if (outResult != null) {
......
}
return res;
}
}
......
}
注意涯曲,從Step 6傳下來的參數(shù)outResult和config均為null,此外在塔,表達式(aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0為false幻件,因此,這里忽略了無關代碼蛔溃。
下面語句對參數(shù)intent的內(nèi)容進行解析绰沥,得到MainActivity的相關信息,保存在aInfo變量中:
ActivityInfo aInfo;
try {
ResolveInfo rInfo =
AppGlobals.getPackageManager().resolveIntent(
intent, resolvedType,
PackageManager.MATCH_DEFAULT_ONLY
| ActivityManagerService.STOCK_PM_FLAGS);
aInfo = rInfo != null ? rInfo.activityInfo : null;
} catch (RemoteException e) {
......
}
解析之后贺待,得到的aInfo.applicationInfo.packageName的值為"shy.luo.activity"徽曲,aInfo.name的值為"shy.luo.activity.MainActivity",這是在這個實例的配置文件AndroidManifest.xml里面配置的麸塞。
此外秃臣,函數(shù)開始的地方調(diào)用intent.getComponent()函數(shù)的返回值不為null,因此哪工,這里的componentSpecified變量為true奥此。
Step 8. ActivityStack.startActivityLocked
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
final int startActivityLocked(IApplicationThread caller,
Intent intent, String resolvedType,
Uri[] grantedUriPermissions,
int grantedMode, ActivityInfo aInfo, IBinder resultTo,
String resultWho, int requestCode,
int callingPid, int callingUid, boolean onlyIfNeeded,
boolean componentSpecified) {
int err = START_SUCCESS;
ProcessRecord callerApp = null;
if (caller != null) {
callerApp = mService.getRecordForAppLocked(caller);
if (callerApp != null) {
callingPid = callerApp.pid;
callingUid = callerApp.info.uid;
} else {
......
}
}
......
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {
int index = indexOfTokenLocked(resultTo);
......
if (index >= 0) {
sourceRecord = (ActivityRecord)mHistory.get(index);
if (requestCode >= 0 && !sourceRecord.finishing) {
......
}
}
}
int launchFlags = intent.getFlags();
if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
&& sourceRecord != null) {
......
}
if (err == START_SUCCESS && intent.getComponent() == null) {
......
}
if (err == START_SUCCESS && aInfo == null) {
......
}
if (err != START_SUCCESS) {
......
}
......
ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
intent, resolvedType, aInfo, mService.mConfiguration,
resultRecord, resultWho, requestCode, componentSpecified);
......
return startActivityUncheckedLocked(r, sourceRecord,
grantedUriPermissions, grantedMode, onlyIfNeeded, true);
}
......
}
從傳進來的參數(shù)caller得到調(diào)用者的進程信息,并保存在callerApp變量中雁比,這里就是Launcher應用程序的進程信息了稚虎。
前面說過,參數(shù)resultTo是Launcher這個Activity里面的一個Binder對象偎捎,通過它可以獲得Launcher這個Activity的相關信息蠢终,保存在sourceRecord變量中。
再接下來茴她,創(chuàng)建即將要啟動的Activity的相關信息寻拂,并保存在r變量中:
ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
intent, resolvedType, aInfo, mService.mConfiguration,
resultRecord, resultWho, requestCode, componentSpecified);
接著調(diào)用startActivityUncheckedLocked函數(shù)進行下一步操作。
Step 9. ActivityStack.startActivityUncheckedLocked
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
final int startActivityUncheckedLocked(ActivityRecord r,
ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
int grantedMode, boolean onlyIfNeeded, boolean doResume) {
final Intent intent = r.intent;
final int callingUid = r.launchedFromUid;
int launchFlags = intent.getFlags();
// We'll invoke onUserLeaving before onPause only if the launching
// activity did not explicitly state that this is an automated launch.
mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
......
ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
!= 0 ? r : null;
// If the onlyIfNeeded flag is set, then we can do this if the activity
// being launched is the same as the one making the call... or, as
// a special case, if we do not know the caller then we count the
// current top activity as the caller.
if (onlyIfNeeded) {
......
}
if (sourceRecord == null) {
......
} else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
......
} else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
......
}
if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
......
}
boolean addingToTask = false;
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
// If bring to front is requested, and no result is requested, and
// we can find a task that was started with this same
// component, then instead of launching bring that one to the front.
if (r.resultTo == null) {
// See if there is a task to bring to the front. If this is
// a SINGLE_INSTANCE activity, there can be one and only one
// instance of it in the history, and it is always in its own
// unique task, so we do a special search.
ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
? findTaskLocked(intent, r.info)
: findActivityLocked(intent, r.info);
if (taskTop != null) {
......
}
}
}
......
if (r.packageName != null) {
// If the activity being launched is the same as the one currently
// at the top, then we need to check if it should only be launched
// once.
ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
if (top != null && r.resultTo == null) {
if (top.realActivity.equals(r.realActivity)) {
......
}
}
} else {
......
}
boolean newTask = false;
// Should this be considered a new task?
if (r.resultTo == null && !addingToTask
&& (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
// todo: should do better management of integers.
mService.mCurTask++;
if (mService.mCurTask <= 0) {
mService.mCurTask = 1;
}
r.task = new TaskRecord(mService.mCurTask, r.info, intent,
(r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
......
newTask = true;
if (mMainStack) {
mService.addRecentTaskLocked(r.task);
}
} else if (sourceRecord != null) {
......
} else {
......
}
......
startActivityLocked(r, newTask, doResume);
return START_SUCCESS;
}
......
}
函數(shù)首先獲得intent的標志值丈牢,保存在launchFlags變量中祭钉。
這個intent的標志值的位Intent.FLAG_ACTIVITY_NO_USER_ACTION沒有置位,因此 赡麦,成員變量mUserLeaving的值為true朴皆。
這個intent的標志值的位Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP也沒有置位帕识,因此泛粹,變量notTop的值為null。
由于在這個例子的AndroidManifest.xml文件中肮疗,MainActivity沒有配置launchMode屬值晶姊,因此,這里的r.launchMode為默認值0伪货,表示以標準(Standard们衙,或者稱為ActivityInfo.LAUNCH_MULTIPLE)的方式來啟動這個Activity钾怔。Activity的啟動方式有四種,其余三種分別是ActivityInfo.LAUNCH_SINGLE_INSTANCE蒙挑、ActivityInfo.LAUNCH_SINGLE_TASK和ActivityInfo.LAUNCH_SINGLE_TOP宗侦,具體可以參考官方網(wǎng)站
傳進來的參數(shù)r.resultTo為null,表示Launcher不需要等這個即將要啟動的MainActivity的執(zhí)行結(jié)果忆蚀。
由于這個intent的標志值的位Intent.FLAG_ACTIVITY_NEW_TASK被置位矾利,而且Intent.FLAG_ACTIVITY_MULTIPLE_TASK沒有置位,因此馋袜,下面的if語句會被執(zhí)行:
if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
(launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
|| r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
// If bring to front is requested, and no result is requested, and
// we can find a task that was started with this same
// component, then instead of launching bring that one to the front.
if (r.resultTo == null) {
// See if there is a task to bring to the front. If this is
// a SINGLE_INSTANCE activity, there can be one and only one
// instance of it in the history, and it is always in its own
// unique task, so we do a special search.
ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
? findTaskLocked(intent, r.info)
: findActivityLocked(intent, r.info);
if (taskTop != null) {
......
}
}
}
這段代碼的邏輯是查看一下男旗,當前有沒有Task可以用來執(zhí)行這個Activity。由于r.launchMode的值不為ActivityInfo.LAUNCH_SINGLE_INSTANCE欣鳖,因此察皇,它通過findTaskLocked函數(shù)來查找存不存這樣的Task,這里返回的結(jié)果是null泽台,即taskTop為null什荣,因此,需要創(chuàng)建一個新的Task來啟動這個Activity怀酷。
接著往下看:
if (r.packageName != null) {
// If the activity being launched is the same as the one currently
// at the top, then we need to check if it should only be launched
// once.
ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
if (top != null && r.resultTo == null) {
if (top.realActivity.equals(r.realActivity)) {
......
}
}
}
這段代碼的邏輯是看一下溃睹,當前在堆棧頂端的Activity是否就是即將要啟動的Activity,有些情況下胰坟,如果即將要啟動的Activity就在堆棧的頂端因篇,那么,就不會重新啟動這個Activity的別一個實例了笔横,具體可以參考官方網(wǎng)站【鹤遥現(xiàn)在處理堆棧頂端的Activity是Launcher,與我們即將要啟動的MainActivity不是同一個Activity吹缔,因此商佑,這里不用進一步處理上述介紹的情況。
執(zhí)行到這里厢塘,我們知道茶没,要在一個新的Task里面來啟動這個Activity了,于是新創(chuàng)建一個Task:
if (r.resultTo == null && !addingToTask
&& (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
// todo: should do better management of integers.
mService.mCurTask++;
if (mService.mCurTask <= 0) {
mService.mCurTask = 1;
}
r.task = new TaskRecord(mService.mCurTask, r.info, intent,
(r.info.flags&ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0);
......
newTask = true;
if (mMainStack) {
mService.addRecentTaskLocked(r.task);
}
}
新建的Task保存在r.task域中晚碾,同時抓半,添加到mService中去,這里的mService就是ActivityManagerService了格嘁。
最后就進入startActivityLocked(r, newTask, doResume)進一步處理了笛求。這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
private final void startActivityLocked(ActivityRecord r, boolean newTask,
boolean doResume) {
final int NH = mHistory.size();
int addPos = -1;
if (!newTask) {
......
}
// Place a new activity at top of stack, so it is next to interact
// with the user.
if (addPos < 0) {
addPos = NH;
}
// If we are not placing the new activity frontmost, we do not want
// to deliver the onUserLeaving callback to the actual frontmost
// activity
if (addPos < NH) {
......
}
// Slot the activity into the history stack and proceed
mHistory.add(addPos, r);
r.inHistory = true;
r.frontOfTask = newTask;
r.task.numActivities++;
if (NH > 0) {
// We want to show the starting preview window if we are
// switching to a new task, or the next activity's process is
// not currently running.
......
} else {
// If this is the first activity, don't do any fancy animations,
// because there is nothing for it to animate on top of.
......
}
......
if (doResume) {
resumeTopActivityLocked(null);
}
}
......
}
這里的NH表示當前系統(tǒng)中歷史任務的個數(shù),這里肯定是大于0,因為Launcher已經(jīng)跑起來了探入。當NH>0時狡孔,并且現(xiàn)在要切換新任務時,要做一些任務切的界面操作蜂嗽,這段代碼我們就不看了苗膝,這里不會影響到下面啟Activity的過程,有興趣的讀取可以自己研究一下植旧。
這里傳進來的參數(shù)doResume為true荚醒,于是調(diào)用resumeTopActivityLocked進一步操作。
Step 10. Activity.resumeTopActivityLocked
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
/**
* Ensure that the top activity in the stack is resumed.
*
* @param prev The previously resumed activity, for when in the process
* of pausing; can be null to call from elsewhere.
*
* @return Returns true if something is being resumed, or false if
* nothing happened.
*/
final boolean resumeTopActivityLocked(ActivityRecord prev) {
// Find the first activity that is not finishing.
ActivityRecord next = topRunningActivityLocked(null);
// Remember how we'll process this pause/resume situation, and ensure
// that the state is reset however we wind up proceeding.
final boolean userLeaving = mUserLeaving;
mUserLeaving = false;
if (next == null) {
......
}
next.delayedResume = false;
// If the top activity is the resumed one, nothing to do.
if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
......
}
// If we are sleeping, and there is no resumed activity, and the top
// activity is paused, well that is the state we want.
if ((mService.mSleeping || mService.mShuttingDown)
&& mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
......
}
......
// If we are currently pausing an activity, then don't do anything
// until that is done.
if (mPausingActivity != null) {
......
}
......
// We need to start pausing the current activity so the top one
// can be resumed...
if (mResumedActivity != null) {
......
startPausingLocked(userLeaving, false);
return true;
}
......
}
......
}
函數(shù)先通過調(diào)用topRunningActivityLocked函數(shù)獲得堆棧頂端的Activity隆嗅,這里就是MainActivity了界阁,這是在上面的Step 9設置好的,保存在next變量中胖喳。
接下來把mUserLeaving的保存在本地變量userLeaving中泡躯,然后重新設置為false,在上面的Step 9中丽焊,mUserLeaving的值為true较剃,因此,這里的userLeaving為true技健。
這里的mResumedActivity為Launcher写穴,因為Launcher是當前正被執(zhí)行的Activity。
當我們處理休眠狀態(tài)時雌贱,mLastPausedActivity保存堆棧頂端的Activity啊送,因為當前不是休眠狀態(tài),所以mLastPausedActivity為null欣孤。
有了這些信息之后馋没,下面的語句就容易理解了:
// If the top activity is the resumed one, nothing to do.
if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
......
}
// If we are sleeping, and there is no resumed activity, and the top
// activity is paused, well that is the state we want.
if ((mService.mSleeping || mService.mShuttingDown)
&& mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
......
}
它首先看要啟動的Activity是否就是當前處理Resumed狀態(tài)的Activity,如果是的話降传,那就什么都不用做篷朵,直接返回就可以了;否則再看一下系統(tǒng)當前是否休眠狀態(tài)婆排,如果是的話声旺,再看看要啟動的Activity是否就是當前處于堆棧頂端的Activity,如果是的話段只,也是什么都不用做腮猖。
上面兩個條件都不滿足,因此翼悴,在繼續(xù)往下執(zhí)行之前缚够,首先要把當處于Resumed狀態(tài)的Activity推入Paused狀態(tài),然后才可以啟動新的Activity鹦赎。但是在將當前這個Resumed狀態(tài)的Activity推入Paused狀態(tài)之前谍椅,首先要看一下當前是否有Activity正在進入Pausing狀態(tài),如果有的話古话,當前這個Resumed狀態(tài)的Activity就要稍后才能進入Paused狀態(tài)了雏吭,這樣就保證了所有需要進入Paused狀態(tài)的Activity串行處理。
這里沒有處于Pausing狀態(tài)的Activity陪踩,即mPausingActivity為null杖们,而且mResumedActivity也不為null,于是就調(diào)用startPausingLocked函數(shù)把Launcher推入Paused狀態(tài)去了肩狂。
Step 11. ActivityStack.startPausingLocked
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
if (mPausingActivity != null) {
......
}
ActivityRecord prev = mResumedActivity;
if (prev == null) {
......
}
......
mResumedActivity = null;
mPausingActivity = prev;
mLastPausedActivity = prev;
prev.state = ActivityState.PAUSING;
......
if (prev.app != null && prev.app.thread != null) {
......
try {
......
prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
prev.configChangeFlags);
......
} catch (Exception e) {
......
}
} else {
......
}
......
}
......
}
函數(shù)首先把mResumedActivity保存在本地變量prev中摘完。在上一步Step 10中,說到mResumedActivity就是Launcher傻谁,因此孝治,這里把Launcher進程中的ApplicationThread對象取出來,通過它來通知Launcher這個Activity它要進入Paused狀態(tài)了审磁。當然谈飒,這里的prev.app.thread是一個ApplicationThread對象的遠程接口,通過調(diào)用這個遠程接口的schedulePauseActivity來通知Launcher進入Paused狀態(tài)态蒂。
參數(shù)prev.finishing表示prev所代表的Activity是否正在等待結(jié)束的Activity列表中杭措,由于Laucher這個Activity還沒結(jié)束,所以這里為false钾恢;參數(shù)prev.configChangeFlags表示哪些config發(fā)生了變化手素,這里我們不關心它的值。
Step 12. ApplicationThreadProxy.schedulePauseActivity
這個函數(shù)定義在frameworks/base/core/java/android/app/ApplicationThreadNative.java文件中:
class ApplicationThreadProxy implements IApplicationThread {
......
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges) throws RemoteException {
Parcel data = Parcel.obtain();
data.writeInterfaceToken(IApplicationThread.descriptor);
data.writeStrongBinder(token);
data.writeInt(finished ? 1 : 0);
data.writeInt(userLeaving ? 1 :0);
data.writeInt(configChanges);
mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,
IBinder.FLAG_ONEWAY);
data.recycle();
}
......
}
這個函數(shù)通過Binder進程間通信機制進入到ApplicationThread.schedulePauseActivity函數(shù)中瘩蚪。
Step 13. ApplicationThread.schedulePauseActivity
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中刑桑,它是ActivityThread的內(nèi)部類:
public final class ActivityThread {
......
private final class ApplicationThread extends ApplicationThreadNative {
......
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges) {
queueOrSendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? 1 : 0),
configChanges);
}
......
}
......
}
這里調(diào)用的函數(shù)queueOrSendMessage是ActivityThread類的成員函數(shù)。
上面說到募舟,這里的finished值為false祠斧,因此,queueOrSendMessage的第一個參數(shù)值為H.PAUSE_ACTIVITY拱礁,表示要暫停token所代表的Activity琢锋,即Launcher。
Step 14. ActivityThread.queueOrSendMessage
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
public final class ActivityThread {
......
private final void queueOrSendMessage(int what, Object obj, int arg1) {
queueOrSendMessage(what, obj, arg1, 0);
}
private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
synchronized (this) {
......
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
mH.sendMessage(msg);
}
}
......
}
這里首先將相關信息組裝成一個msg呢灶,然后通過mH成員變量發(fā)送出去吴超,mH的類型是H,繼承于Handler類鸯乃,是ActivityThread的內(nèi)部類鲸阻,因此跋涣,這個消息最后由H.handleMessage來處理。
Step 15. H.handleMessage
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
public final class ActivityThread {
......
private final class H extends Handler {
......
public void handleMessage(Message msg) {
......
switch (msg.what) {
......
case PAUSE_ACTIVITY:
handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
maybeSnapshot();
break;
......
}
......
}
......
}
這里調(diào)用ActivityThread.handlePauseActivity進一步操作鸟悴,msg.obj是一個ActivityRecord對象的引用陈辱,它代表的是Launcher這個Activity。
Step 16. ActivityThread.handlePauseActivity
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
public final class ActivityThread {
......
private final void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges) {
ActivityClientRecord r = mActivities.get(token);
if (r != null) {
//Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
if (userLeaving) {
performUserLeavingActivity(r);
}
r.activity.mConfigChangeFlags |= configChanges;
Bundle state = performPauseActivity(token, finished, true);
// Make sure any pending writes are now committed.
QueuedWork.waitToFinish();
// Tell the activity manager we have paused.
try {
ActivityManagerNative.getDefault().activityPaused(token, state);
} catch (RemoteException ex) {
}
}
}
......
}
函數(shù)首先將Binder引用token轉(zhuǎn)換成ActivityRecord的遠程接口ActivityClientRecord细诸,然后做了三個事情:1. 如果userLeaving為true沛贪,則通過調(diào)用performUserLeavingActivity函數(shù)來調(diào)用Activity.onUserLeaveHint通知Activity,用戶要離開它了震贵;2. 調(diào)用performPauseActivity函數(shù)來調(diào)用Activity.onPause函數(shù)利赋,我們知道,在Activity的生命周期中猩系,當它要讓位于其它的Activity時媚送,系統(tǒng)就會調(diào)用它的onPause函數(shù);3. 它通知ActivityManagerService寇甸,這個Activity已經(jīng)進入Paused狀態(tài)了季希,ActivityManagerService現(xiàn)在可以完成未竟的事情,即啟動MainActivity了幽纷。
Step 17. ActivityManagerProxy.activityPaused
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:
class ActivityManagerProxy implements IActivityManager
{
......
public void activityPaused(IBinder token, Bundle state) throws RemoteException
{
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(token);
data.writeBundle(state);
mRemote.transact(ACTIVITY_PAUSED_TRANSACTION, data, reply, 0);
reply.readException();
data.recycle();
reply.recycle();
}
......
}
這里通過Binder進程間通信機制就進入到ActivityManagerService.activityPaused函數(shù)中去了式塌。
Step 18. ActivityManagerService.activityPaused
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
public final void activityPaused(IBinder token, Bundle icicle) {
......
final long origId = Binder.clearCallingIdentity();
mMainStack.activityPaused(token, icicle, false);
......
}
......
}
這里,又再次進入到ActivityStack類中友浸,執(zhí)行activityPaused函數(shù)峰尝。
Step 19. ActivityStack.activityPaused
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
final void activityPaused(IBinder token, Bundle icicle, boolean timeout) {
......
ActivityRecord r = null;
synchronized (mService) {
int index = indexOfTokenLocked(token);
if (index >= 0) {
r = (ActivityRecord)mHistory.get(index);
if (!timeout) {
r.icicle = icicle;
r.haveState = true;
}
mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
if (mPausingActivity == r) {
r.state = ActivityState.PAUSED;
completePauseLocked();
} else {
......
}
}
}
}
......
}
這里通過參數(shù)token在mHistory列表中得到ActivityRecord,從上面我們知道收恢,這個ActivityRecord代表的是Launcher這個Activity武学,而我們在Step 11中,把Launcher這個Activity的信息保存在mPausingActivity中伦意,因此火窒,這里mPausingActivity等于r,于是驮肉,執(zhí)行completePauseLocked操作熏矿。
Step 20. ActivityStack.completePauseLocked
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
private final void completePauseLocked() {
ActivityRecord prev = mPausingActivity;
......
if (prev != null) {
......
mPausingActivity = null;
}
if (!mService.mSleeping && !mService.mShuttingDown) {
resumeTopActivityLocked(prev);
} else {
......
}
......
}
......
}
函數(shù)首先把mPausingActivity變量清空,因為現(xiàn)在不需要它了离钝,然后調(diào)用resumeTopActivityLokced進一步操作票编,它傳入的參數(shù)即為代表Launcher這個Activity的ActivityRecord。
Step 21. ActivityStack.resumeTopActivityLokced
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
final boolean resumeTopActivityLocked(ActivityRecord prev) {
......
// Find the first activity that is not finishing.
ActivityRecord next = topRunningActivityLocked(null);
// Remember how we'll process this pause/resume situation, and ensure
// that the state is reset however we wind up proceeding.
final boolean userLeaving = mUserLeaving;
mUserLeaving = false;
......
next.delayedResume = false;
// If the top activity is the resumed one, nothing to do.
if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
......
return false;
}
// If we are sleeping, and there is no resumed activity, and the top
// activity is paused, well that is the state we want.
if ((mService.mSleeping || mService.mShuttingDown)
&& mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
......
return false;
}
.......
// We need to start pausing the current activity so the top one
// can be resumed...
if (mResumedActivity != null) {
......
return true;
}
......
if (next.app != null && next.app.thread != null) {
......
} else {
......
startSpecificActivityLocked(next, true, true);
}
return true;
}
......
}
通過上面的Step 9卵渴,我們知道溜腐,當前在堆棧頂端的Activity為我們即將要啟動的MainActivity撩鹿,這里通過調(diào)用topRunningActivityLocked將它取回來箫老,保存在next變量中。之前最后一個Resumed狀態(tài)的Activity辛藻,即Launcher,到了這里已經(jīng)處于Paused狀態(tài)了互订,因此吱肌,mResumedActivity為null。最后一個處于Paused狀態(tài)的Activity為Launcher屁奏,因此岩榆,這里的mLastPausedActivity就為Launcher错负。前面我們?yōu)镸ainActivity創(chuàng)建了ActivityRecord后坟瓢,它的app域一直保持為null。有了這些信息后犹撒,上面這段代碼就容易理解了折联,它最終調(diào)用startSpecificActivityLocked進行下一步操作。
Step 22. ActivityStack.startSpecificActivityLocked
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
private final 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);
......
if (app != null && app.thread != null) {
try {
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
......
}
}
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false);
}
......
}
注意识颊,這里由于是第一次啟動應用程序的Activity诚镰,所以下面語句:
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid);
取回來的app為null。在Activity應用程序中的AndroidManifest.xml配置文件中祥款,我們沒有指定Application標簽的process屬性清笨,系統(tǒng)就會默認使用package的名稱,這里就是"shy.luo.activity"了刃跛。每一個應用程序都有自己的uid抠艾,因此,這里uid + process的組合就可以為每一個應用程序創(chuàng)建一個ProcessRecord桨昙。當然检号,我們可以配置兩個應用程序具有相同的uid和package,或者在AndroidManifest.xml配置文件的application標簽或者activity標簽中顯式指定相同的process屬性值蛙酪,這樣齐苛,不同的應用程序也可以在同一個進程中啟動。
函數(shù)最終執(zhí)行ActivityManagerService.startProcessLocked函數(shù)進行下一步操作桂塞。
Step 23. ActivityManagerService.startProcessLocked
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
String hostingType, ComponentName hostingName, boolean allowWhileBooting) {
ProcessRecord app = getProcessRecordLocked(processName, info.uid);
......
String hostingNameStr = hostingName != null
? hostingName.flattenToShortString() : null;
......
if (app == null) {
app = new ProcessRecordLocked(null, info, processName);
mProcessNames.put(processName, info.uid, app);
} else {
// If this is a new package in the process, add the package to the list
app.addPackage(info.packageName);
}
......
startProcessLocked(app, hostingType, hostingNameStr);
return (app.pid != 0) ? app : null;
}
......
}
這里再次檢查是否已經(jīng)有以process + uid命名的進程存在凹蜂,在我們這個情景中,返回值app為null阁危,因此炊甲,后面會創(chuàng)建一個ProcessRecord,并存保存在成員變量mProcessNames中欲芹,最后卿啡,調(diào)用另一個startProcessLocked函數(shù)進一步操作:
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
private final void startProcessLocked(ProcessRecord app,
String hostingType, String hostingNameStr) {
......
try {
int uid = app.info.uid;
int[] gids = null;
try {
gids = mContext.getPackageManager().getPackageGids(
app.info.packageName);
} catch (PackageManager.NameNotFoundException e) {
......
}
......
int debugFlags = 0;
......
int pid = Process.start("android.app.ActivityThread",
mSimpleProcessManagement ? app.processName : null, uid, uid,
gids, debugFlags, null);
......
} catch (RuntimeException e) {
......
}
}
......
}
這里主要是調(diào)用Process.start接口來創(chuàng)建一個新的進程,新的進程會導入android.app.ActivityThread類菱父,并且執(zhí)行它的main函數(shù)颈娜,這就是為什么我們前面說每一個應用程序都有一個ActivityThread實例來對應的原因剑逃。
Step 24. ActivityThread.main
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
public final class ActivityThread {
......
private final void attach(boolean system) {
......
mSystemThread = system;
if (!system) {
......
IActivityManager mgr = ActivityManagerNative.getDefault();
try {
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
}
} else {
......
}
}
......
public static final void main(String[] args) {
.......
ActivityThread thread = new ActivityThread();
thread.attach(false);
......
Looper.loop();
.......
thread.detach();
......
}
}
這個函數(shù)在進程中創(chuàng)建一個ActivityThread實例,然后調(diào)用它的attach函數(shù)官辽,接著就進入消息循環(huán)了蛹磺,直到最后進程退出。
函數(shù)attach最終調(diào)用了ActivityManagerService的遠程接口ActivityManagerProxy的attachApplication函數(shù)同仆,傳入的參數(shù)是mAppThread萤捆,這是一個ApplicationThread類型的Binder對象,它的作用是用來進行進程間通信的俗批。
Step 25. ActivityManagerProxy.attachApplication
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:
class ActivityManagerProxy implements IActivityManager
{
......
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();
}
......
}
這里通過Binder驅(qū)動程序俗或,最后進入ActivityManagerService的attachApplication函數(shù)中。
Step 26. ActivityManagerService.attachApplication
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
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);
}
}
......
}
這里將操作轉(zhuǎn)發(fā)給attachApplicationLocked函數(shù)岁忘。
Step 27. ActivityManagerService.attachApplicationLocked
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid) {
// Find the application record that is being attached... either via
// the pid if we are running in multiple processes, or just pull the
// next app record if we are emulating process with anonymous threads.
ProcessRecord app;
if (pid != MY_PID && pid >= 0) {
synchronized (mPidsSelfLocked) {
app = mPidsSelfLocked.get(pid);
}
} else if (mStartingProcesses.size() > 0) {
......
} else {
......
}
if (app == null) {
......
return false;
}
......
String processName = app.processName;
try {
thread.asBinder().linkToDeath(new AppDeathRecipient(
app, pid, thread), 0);
} catch (RemoteException e) {
......
return false;
}
......
app.thread = thread;
app.curAdj = app.setAdj = -100;
app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
app.forcingToForeground = null;
app.foregroundServices = false;
app.debugging = false;
......
boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
......
boolean badApp = false;
boolean didSomething = false;
// See if the top visible activity is waiting to run in this process...
ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
if (hr != null && normalMode) {
if (hr.app == null && app.info.uid == hr.info.applicationInfo.uid
&& processName.equals(hr.processName)) {
try {
if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
didSomething = true;
}
} catch (Exception e) {
......
}
} else {
......
}
}
......
return true;
}
......
}
在前面的Step 23中辛慰,已經(jīng)創(chuàng)建了一個ProcessRecord,這里首先通過pid將它取回來干像,放在app變量中帅腌,然后對app的其它成員進行初始化,最后調(diào)用mMainStack.realStartActivityLocked執(zhí)行真正的Activity啟動操作麻汰。這里要啟動的Activity通過調(diào)用mMainStack.topRunningActivityLocked(null)從堆棧頂端取回來速客,這時候在堆棧頂端的Activity就是MainActivity了。
Step 28. ActivityStack.realStartActivityLocked
這個函數(shù)定義在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中:
public class ActivityStack {
......
final boolean realStartActivityLocked(ActivityRecord r,
ProcessRecord app, boolean andResume, boolean checkConfig)
throws RemoteException {
......
r.app = app;
......
int idx = app.activities.indexOf(r);
if (idx < 0) {
app.activities.add(r);
}
......
try {
......
List<ResultInfo> results = null;
List<Intent> newIntents = null;
if (andResume) {
results = r.results;
newIntents = r.newIntents;
}
......
app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
System.identityHashCode(r),
r.info, r.icicle, results, newIntents, !andResume,
mService.isNextTransitionForward());
......
} catch (RemoteException e) {
......
}
......
return true;
}
......
}
這里最終通過app.thread進入到ApplicationThreadProxy的scheduleLaunchActivity函數(shù)中五鲫,注意溺职,這里的第二個參數(shù)r,是一個ActivityRecord類型的Binder對象臣镣,用來作來這個Activity的token值辅愿。
Step 29. ApplicationThreadProxy.scheduleLaunchActivity
這個函數(shù)定義在frameworks/base/core/java/android/app/ApplicationThreadNative.java文件中:
class ApplicationThreadProxy implements IApplicationThread {
......
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward)
throws RemoteException {
Parcel data = Parcel.obtain();
data.writeInterfaceToken(IApplicationThread.descriptor);
intent.writeToParcel(data, 0);
data.writeStrongBinder(token);
data.writeInt(ident);
info.writeToParcel(data, 0);
data.writeBundle(state);
data.writeTypedList(pendingResults);
data.writeTypedList(pendingNewIntents);
data.writeInt(notResumed ? 1 : 0);
data.writeInt(isForward ? 1 : 0);
mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
IBinder.FLAG_ONEWAY);
data.recycle();
}
......
這個函數(shù)最終通過Binder驅(qū)動程序進入到ApplicationThread的scheduleLaunchActivity函數(shù)中。
Step 30. ApplicationThread.scheduleLaunchActivity
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
public final class ActivityThread {
......
private final class ApplicationThread extends ApplicationThreadNative {
......
// we use token to identify this activity without having to send the
// activity itself back to the activity manager. (matters more with ipc)
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward) {
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
r.activityInfo = info;
r.state = state;
r.pendingResults = pendingResults;
r.pendingIntents = pendingNewIntents;
r.startsNotResumed = notResumed;
r.isForward = isForward;
queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
}
......
}
......
}
函數(shù)首先創(chuàng)建一個ActivityClientRecord實例忆某,并且初始化它的成員變量点待,然后調(diào)用ActivityThread類的queueOrSendMessage函數(shù)進一步處理。
Step 31. ActivityThread.queueOrSendMessage
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
public final class ActivityThread {
......
private final class ApplicationThread extends ApplicationThreadNative {
......
// if the thread hasn't started yet, we don't have the handler, so just
// save the messages until we're ready.
private final void queueOrSendMessage(int what, Object obj) {
queueOrSendMessage(what, obj, 0, 0);
}
......
private final void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
synchronized (this) {
......
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
mH.sendMessage(msg);
}
}
......
}
......
}
函數(shù)把消息內(nèi)容放在msg中弃舒,然后通過mH把消息分發(fā)出去癞埠,這里的成員變量mH我們在前面已經(jīng)見過,消息分發(fā)出去后聋呢,最后會調(diào)用H類的handleMessage函數(shù)苗踪。
Step 32. H.handleMessage
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
public final class ActivityThread {
......
private final class H extends Handler {
......
public void handleMessage(Message msg) {
......
switch (msg.what) {
case LAUNCH_ACTIVITY: {
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo);
handleLaunchActivity(r, null);
} break;
......
}
......
}
......
}
這里最后調(diào)用ActivityThread類的handleLaunchActivity函數(shù)進一步處理。
Step 33. ActivityThread.handleLaunchActivity
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
public final class ActivityThread {
......
private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
handleResumeActivity(r.token, false, r.isForward);
......
} else {
......
}
}
......
}
這里首先調(diào)用performLaunchActivity函數(shù)來加載這個Activity類削锰,即shy.luo.activity.MainActivity通铲,然后調(diào)用它的onCreate函數(shù),最后回到handleLaunchActivity函數(shù)時器贩,再調(diào)用handleResumeActivity函數(shù)來使這個Activity進入Resumed狀態(tài)颅夺,即會調(diào)用這個Activity的onResume函數(shù)朋截,這是遵循Activity的生命周期的。
Step 34. ActivityThread.performLaunchActivity
這個函數(shù)定義在frameworks/base/core/java/android/app/ActivityThread.java文件中:
public final class ActivityThread {
......
private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
r.intent.setExtrasClassLoader(cl);
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
......
}
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
......
if (activity != null) {
ContextImpl appContext = new ContextImpl();
appContext.init(r.packageInfo, r.token, this);
appContext.setOuterContext(activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mConfiguration);
......
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstance,
r.lastNonConfigurationChildInstances, config);
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstance = null;
r.lastNonConfigurationChildInstances = null;
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
mInstrumentation.callActivityOnCreate(activity, r.state);
......
r.activity = activity;
r.stopped = true;
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
if (!r.activity.mFinished) {
if (r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
if (!r.activity.mFinished) {
activity.mCalled = false;
mInstrumentation.callActivityOnPostCreate(activity, r.state);
if (!activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onPostCreate()");
}
}
}
r.paused = true;
mActivities.put(r.token, r);
} catch (SuperNotCalledException e) {
......
} catch (Exception e) {
......
}
return activity;
}
......
}
函數(shù)前面是收集要啟動的Activity的相關信息吧黄,主要package和component信息:
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
然后通過ClassLoader將shy.luo.activity.MainActivity類加載進來:
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
r.intent.setExtrasClassLoader(cl);
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
......
}
接下來是創(chuàng)建Application對象部服,這是根據(jù)AndroidManifest.xml配置文件中的Application標簽的信息來創(chuàng)建的:
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
后面的代碼主要創(chuàng)建Activity的上下文信息,并通過attach方法將這些上下文信息設置到MainActivity中去:
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstance,
r.lastNonConfigurationChildInstances, config);
最后還要調(diào)用MainActivity的onCreate函數(shù):
mInstrumentation.callActivityOnCreate(activity, r.state);
這里不是直接調(diào)用MainActivity的onCreate函數(shù)拗慨,而是通過mInstrumentation的callActivityOnCreate函數(shù)來間接調(diào)用廓八,前面我們說過,mInstrumentation在這里的作用是監(jiān)控Activity與系統(tǒng)的交互操作赵抢,相當于是系統(tǒng)運行日志剧蹂。
Step 35. MainActivity.onCreate
這個函數(shù)定義在packages/experimental/Activity/src/shy/luo/activity/MainActivity.java文件中,這是我們自定義的app工程文件:
public class MainActivity extends Activity implements OnClickListener {
......
@Override
public void onCreate(Bundle savedInstanceState) {
......
Log.i(LOG_TAG, "Main Activity Created.");
}
......
}
這樣昌讲,MainActivity就啟動起來了国夜,整個應用程序也啟動起來了减噪。
總結(jié)
整個應用程序的啟動過程要執(zhí)行很多步驟短绸,但是整體來看,主要分為以下五個階段:
一. Step1 - Step 11:Launcher通過Binder進程間通信機制通知ActivityManagerService筹裕,它要啟動一個Activity醋闭;
二. Step 12 - Step 16:ActivityManagerService通過Binder進程間通信機制通知Launcher進入Paused狀態(tài);
三. Step 17 - Step 24:Launcher通過Binder進程間通信機制通知ActivityManagerService朝卒,它已經(jīng)準備就緒進入Paused狀態(tài)证逻,于是ActivityManagerService就創(chuàng)建一個新的進程,用來啟動一個ActivityThread實例抗斤,即將要啟動的Activity就是在這個ActivityThread實例中運行囚企;
四. Step 25 - Step 27:ActivityThread通過Binder進程間通信機制將一個ApplicationThread類型的Binder對象傳遞給ActivityManagerService,以便以后ActivityManagerService能夠通過這個Binder對象和它進行通信瑞眼;
五. Step 28 - Step 35:ActivityManagerService通過Binder進程間通信機制通知ActivityThread龙宏,現(xiàn)在一切準備就緒,它可以真正執(zhí)行Activity的啟動操作了伤疙。