参考http://blog.csdn.net/luoshengyang/article/details/6689748
servicemanager(用来管理系统中所有的binder service,不管是本地的c++实现的还是java语言实现的都需要这个进程来统一管理,最主要的管理就是,注册添加服务,获取服务)
Zygote main--->init1(system_init)--->init2(systemThread)->((ActivityManagerService)ActivityManagerNative.getDefault()).systemReady(.)
public void systemReady(final Runnable goingCallback) {
…
if (mSystemReady) {
if (goingCallback != null) goingCallback.run();
return; // 执行回调
}
…
resumeTopActivityLocked(null);
}
private final boolean resumeTopActivityLocked(HistoryRecord prev) {
…
if (next == null) {
// There are no more activities! Let's just start up the
// Launcher...
return startHomeActivityLocked();
}
…
}
private boolean startHomeActivityLocked() {
…
if (aInfo != null) {
…
if (app == null || app.instrumentationClass == null) {
intent.setFlags(intent.getFlags() |
Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityLocked(null, intent, null, null, 0, aInfo,
null, null, 0, 0, 0, false, false); // 这里启动home Launcher
}
}
…
}
1. Launcher.startActivitySafely //Launcher继承自Activity
public final class Launcher extends Activity
implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, AllAppsView.Watcher
{
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); //开始进行Activity.startActivity
} catch (ActivityNotFoundException e) {
......
} catch (SecurityException e) {
......
}
}
}
2. Activity startActivity -> startActivityForResult
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks {
......
@Override
public void startActivity(Intent intent) {
startActivityForResult(intent, -1);
}
public void startActivityForResult(Intent intent, int requestCode) {
if (mParent == null) {
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this,
//Binder对象,ActivityManagerService会使用它来和ActivityThread来进行进程间通信,
//些时还在Launcher中mMainThread代表的是Launcher应用程序运行的进程
mMainThread.getApplicationThread(),
mToken, // 代表Activity的IBinder对像,在Activity.attach中被赋值
this,
intent, requestCode);
......
} else {
......
}
......
}
3. 进入Instrumentation
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 {
//ActivityManagerService的远程接口,即ActivityManagerProxy接口
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;
}
......
}
4. ActivityManagerProxy.startActivity
这个函数定义在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); //传intent
data.writeString(resolvedType);
data.writeTypedArray(grantedUriPermissions, 0);
data.writeInt(grantedMode);
data.writeStrongBinder(resultTo); //发起调用的Activity 的IBinder对像
data.writeString(resultWho);
data.writeInt(requestCode);
data.writeInt(onlyIfNeeded ? 1 : 0);
data.writeInt(debug ? 1 : 0);
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0); //IPC调用ActivityManagerService.startActivity
reply.readException();
int result = reply.readInt();
reply.recycle();
data.recycle();
return result;
}
......
}
5. ActivityManagerService.startActivity//AMS另一个进程
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, //发起调用的Activity 的IBinder对像
String resultWho, int requestCode, boolean onlyIfNeeded,
boolean debug) {
return mMainStack.startActivityMayWait( //mMainStack的类型为ActivityStack
caller, intent, resolvedType,
grantedUriPermissions, grantedMode, resultTo, resultWho,
requestCode, onlyIfNeeded, debug, null, null);
}
......
}
6. ActivityStack.startActivityMayWait
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中
public class ActivityStack {
......
//step 1
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.
//对参数intent的内容进行解析,得到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) {
......
}
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, //进入startActivityLocked
grantedUriPermissions, grantedMode, aInfo,
resultTo, resultWho, requestCode, callingPid, callingUid,
onlyIfNeeded, componentSpecified);
if (mConfigWillChange && mMainStack) {
......
}
......
if (outResult != null) {
......
}
return res;
}
}
//step 2
final int startActivityLocked(
IApplicationThread caller, //调用者的进程信息Launcher
Intent intent, String resolvedType,
Uri[] grantedUriPermissions,
int grantedMode, ActivityInfo aInfo,
IBinder resultTo, //执行调用的 Activity.mToken 是一个IBinder对象(从Launcher启动的话就是Launcher这个Activity里面的一个Binder对象)
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); //caller得到调用者的进程信息,并保存在callerApp变量中,这里就是Launcher应用程序的进程信息了。
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
);
}
//step 3
final int startActivityUncheckedLocked(
ActivityRecord r,
ActivityRecord sourceRecord, //调用者的Record
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;
}
//step 4
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);
}
}
//step 5
/**
* 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;
}
......
}
//step 6
private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
if (mPausingActivity != null) {
......
}
ActivityRecord prev = mResumedActivity; //当前激活的Activity
if (prev == null) {
......
}
......
mResumedActivity = null; //当前激活的Activity设置为null
mPausingActivity = prev; //原当前激活的Activity设置暂停!!
mLastPausedActivity = prev;
prev.state = ActivityState.PAUSING;
......
if (prev.app != null && prev.app.thread != null) {
......
try {
......
prev.app.thread.schedulePauseActivity(//原当前Activity进入暂停状态
prev, prev.finishing, userLeaving,
prev.configChangeFlags);
......
} catch (Exception e) {
......
}
} else {
......
}
......
}
......
}
7.1. ApplicationThreadProxy.schedulePauseActivity
这个函数定义在frameworks/base/core/java/android/app/ApplicationThreadNative.java文件中
//!!!此时是在prev.app.thread中!!!
//setp 1
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( //prev.app.thread中的IPC调用!!
SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,
IBinder.FLAG_ONEWAY);
data.recycle();
}
......
}
//setp 2
public abstract class ApplicationThreadNative extends Binder
implements IApplicationThread {
static public IApplicationThread asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IApplicationThread in =
(IApplicationThread)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
return new ApplicationThreadProxy(obj);
}
public ApplicationThreadNative() {
attachInterface(this, descriptor);
}
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)//prev Activity的进程!!
throws RemoteException {
switch (code) {
case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION:// 调用到这里
{
data.enforceInterface(IApplicationThread.descriptor);
IBinder b = data.readStrongBinder();
boolean finished = data.readInt() != 0;
boolean userLeaving = data.readInt() != 0;
int configChanges = data.readInt();
schedulePauseActivity(b, finished, userLeaving, configChanges);
return true;
}
......
}
return super.onTransact(code, data, reply, flags);
}
public IBinder asBinder()
{
return this;
}
}
7.2 ApplicationThread.schedulePauseActivity
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中,它是ActivityThread的内部类
//重新进入之前的Activity的进程
public final class ActivityThread {
......
//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);
}
......
}
......
}
8. ActivityThread.queueOrSendMessage
这个函数定义在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);
}
}
......
}
9. H.handleMessage //ActivityThread的内部类
这个函数定义在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;
......
}
......
}
......
}
10. ActivityThread.handlePauseActivity
这个函数定义在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); //在performLaunchActivity函数中启动Activity成功后,会执行mActivities.put(r.token, r);
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); //暂停Activity
// Make sure any pending writes are now committed.
QueuedWork.waitToFinish();
// Tell the activity manager we have paused.
try {
ActivityManagerNative.getDefault().activityPaused(token, state); //Activity需要IPC通知ASM才能暂停
} catch (RemoteException ex) {
}
}
}
......
}
11.ActivityManagerProxy.activityPaused
这个函数定义在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); //完成暂Pause停后IPC通知AMS
reply.readException();
data.recycle();
reply.recycle();
}
......
}
12.ActivityManagerService.activityPaused //再次进入AMS 进程中
这个函数定义在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类中,执行activityPaused函数。
......
}
......
}
13. ActivityStack.activityPaused 任务栈操作
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中
public class ActivityStack {
......
//step 1
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 {
......
}
}
}
}
//step 2
private final void completePauseLocked() {
ActivityRecord prev = mPausingActivity;
......
if (prev != null) {
......
mPausingActivity = null;
}
if (!mService.mSleeping && !mService.mShuttingDown) {
resumeTopActivityLocked(prev);
} else {
......
}
......
}
//step 3
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 4
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( //AMS!!
r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false);
}
......
}
14. ActivityManagerService.startProcessLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
//step 1
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;
}
//step 2
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;
......
//创建一个新的进程,新的进程会导入android.app.ActivityThread类,并且执行它的main函数, !!!
//这就是为什么我们前面说每一个应用程序都有一个ActivityThread实例来对应的原因 !!!
int pid = Process.start("android.app.ActivityThread",
mSimpleProcessManagement ? app.processName : null, uid, uid,
gids, debugFlags, null);
......
} catch (RuntimeException e) {
......
}
}
......
}
15. ActivityThread.main //新进程中
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中
public final class ActivityThread {
......
//step 1
public static final void main(String[] args) {
.......
ActivityThread thread = new ActivityThread();
thread.attach(false);
......
//step 3
Looper.loop();
.......
thread.detach();
......
}
//step 2
private final void attach(boolean system) {
......
mSystemThread = system;
if (!system) {
......
// 3.1 ActivityManagerNative.getDefault()返回的是ActivityManagerProxy的实例,
// 它只是一个代理类,这个代理类实际上代理的是IBinder b = ServiceManager.getService("activity");
// 这个Service。
// 3.2 这个Service是什么时候添加进来的呢?
// 在SystemServer.java的run()中有调用
// ActivityManagerService.setSystemProcess();
// ServiceManager.addService("activity", m);
// 这里还会添加许多系统关键服务。
IActivityManager mgr = ActivityManagerNative.getDefault(); //AMS
try {
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
}
} else {
......
}
}
......
}
16. ActivityManagerProxy.attachApplication
这个函数定义在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中
//ActivityManagerProxy是ActivityManagerNative的代理
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); //AMS IPC调用
reply.readException();
data.recycle();
reply.recycle();
}
......
}
17.1 ActivityManagerNative.onTransact //IPC进入另一个进程
//step 1
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
........
case ATTACH_APPLICATION_TRANSACTION: {
data.enforceInterface(IActivityManager.descriptor);
IApplicationThread app = ApplicationThreadNative.asInterface(
data.readStrongBinder()); //将发起调用的Binder封成ApplicationThreadProxy!!!这里的Binder就是Process.start启动的ActivityThread!!
if (app != null) {
attachApplication(app);
}
reply.writeNoException();
return true;
}
........
}
........
}
}
//step 2
public abstract class ApplicationThreadNative extends Binder
implements IApplicationThread {
/**
* Cast a Binder object into an application thread interface, generating
* a proxy if needed.
*/
static public IApplicationThread asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IApplicationThread in =
(IApplicationThread)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
return new ApplicationThreadProxy(obj);
}
........
}
17.2 ActivityManagerService.attachApplication
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件
public final class ActivityManagerService extends ActivityManagerNative
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
......
//step 1
public final void attachApplication(IApplicationThread thread) {
synchronized (this) {
//1.线程A通过Binder远程调用线程B:则线程B的IPCThreadState中的mCallingUid和mCallingPid保存的就是线程A的UID和PID。
//这时在线程B中调用Binder.getCallingPid()和Binder.getCallingUid()方法便可获取线程A的UID和PID,
//然后利用UID和PID进行权限比对,判断线程A是否有权限调用线程B的某个方法。
//2.线程B通过Binder调用当前线程的某个组件:此时线程B是线程B某个组件的调用端,
//则mCallingUid和mCallingPid应该保存当前线程B的PID和UID,
//故需要调用clearCallingIdentity()方法完成这个功能。
//当线程B调用完某个组件,由于线程B仍然处于线程A的被调用端,
//因此mCallingUid和mCallingPid需要恢复成线程A的UID和PID,
//这时调用restoreCallingIdentity()即可完成。
int callingPid = Binder.getCallingPid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid);
Binder.restoreCallingIdentity(origId);
}
}
//step 2
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; // 发起调用的Binder ActivityThread
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)) { //mMainStack任务栈
didSomething = true;
}
} catch (Exception e) {
......
}
} else {
......
}
}
......
return true;
}
......
}
18.1 ActivityStack.realStartActivityLocked
这个函数定义在frameworks/base/services/java/com/android/server/am/ActivityStack.java文件中
public class ActivityStack {
......
final boolean realStartActivityLocked(
ActivityRecord r,
ProcessRecord app, // 发起调用的Binder app.thread=ActivityThread
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(// 这里调用的是ApplicationThreadProxy.scheduleLaunchActivity
new Intent(r.intent),
r, //token
System.identityHashCode(r),
r.info, r.icicle, results, newIntents, !andResume,
mService.isNextTransitionForward());
......
} catch (RemoteException e) {
......
}
......
return true;
}
......
}
18.2 ApplicationThreadProxy.scheduleLaunchActivity
class ApplicationThreadProxy implements IApplicationThread {
......
public final void scheduleLaunchActivity(
Intent intent,
IBinder token, //ActivityRecord
int ident,
ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
int procState, Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler)
throws RemoteException {
Parcel data = Parcel.obtain();
data.writeInterfaceToken(IApplicationThread.descriptor);
intent.writeToParcel(data, 0);
data.writeStrongBinder(token);
data.writeInt(ident);
info.writeToParcel(data, 0);
curConfig.writeToParcel(data, 0);
compatInfo.writeToParcel(data, 0);
data.writeInt(procState);
data.writeBundle(state);
data.writeTypedList(pendingResults);
data.writeTypedList(pendingNewIntents);
data.writeInt(notResumed ? 1 : 0);
data.writeInt(isForward ? 1 : 0);
data.writeString(profileName);
if (profileFd != null) {
data.writeInt(1);
profileFd.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
data.writeInt(0);
}
data.writeInt(autoStopProfiler ? 1 : 0);
mRemote.transact( // 再次IPC调用返回发起调用的ActivityThread!!!
SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
IBinder.FLAG_ONEWAY);
data.recycle();
}
......
}
19. ApplicationThread.scheduleLaunchActivity ///回到ActivityThread进程中
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中
public final class ActivityThread {
......
private final class ApplicationThread extends ApplicationThreadNative {
......
//step 1
// 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);
}
//step 2
// 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);
}
//step 3
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);
}
}
......
}
......
}
20. H.handleMessage
这个函数定义在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;
......
}
......
}
......
}
21. ActivityThread.handleLaunchActivity
这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中
public final class ActivityThread {
......
//step 1
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 {
......
}
}
//step 2
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();
//在ActivityThread中 根据IPC传进来的intent加载对应的Activity,所以说先有ActivityThread再有Activity!!
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); //r.token ActivityRecord 根据包和Activity信息init
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); //调用Activity的onCreate函数,正式启动Activity 见22
......
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); //调用Activity的OnRestoreInstanceState
}
}
if (!r.activity.mFinished) {
activity.mCalled = false;
mInstrumentation.callActivityOnPostCreate(activity, r.state); //调用Activity的OnPostCreate
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;
}
......
}
22. Instrumentation.callActivityOnCreate
文件在\frameworks\base\core\java\android\app\Instrumentation.java
public class Instrumentation {
......
public void callActivityOnCreate(Activity activity, Bundle icicle) {
if (mWaitingActivities != null) {
synchronized (mSync) {
final int N = mWaitingActivities.size();
for (int i=0; i<N; i++) {
final ActivityWaiter aw = mWaitingActivities.get(i);
final Intent intent = aw.intent;
if (intent.filterEquals(activity.getIntent())) {
aw.activity = activity;
mMessageQueue.addIdleHandler(new ActivityGoing(aw));
}
}
}
}
activity.performCreate(icicle);//在这里调用onCreate!!!
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
am.match(activity, activity, activity.getIntent());
}
}
}
}
......
}
23. Activity.performCreate
文件在\android-4.4w_r1\frameworks\base\core\java\android\app\Activity.java
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2 {
private static final String TAG = "Activity";
......
final void performCreate(Bundle icicle) {
onCreate(icicle);
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mFragments.dispatchActivityCreated();
}
......
}