startActivity(new Intent(MainActivity.this,SecondActivity.class));
系统对四大组件的内部工作进行了封装,当然activity也不例外。一句简单的代码就开启了activity。然而他的内部工作流程我们不一定明白:activity对象是在何时创建的呢?onCreate方法又是在何时被系统回调呢?相信我们明白了这些内部的机制,我们的技术会有进一步的提高!!!
主要分析activity的启动流程。(启动模式、任务栈可以自行看下)
// 开启单个Activity的
public void startActivity(Intent intent)// 内部调用了下面的两参数开启方式
public void startActivity(Intent intent, @Nullable Bundle options) // 内部调用了startActivityForResult
// 等等 。。。
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
Activity的开启方式有很多,但是你仔细跟踪下方法(ctrl+鼠标右键)你就会发现:这些方法最终调用startActivityForResult。
//三个参数的
public void startActivityForResult(@RequiresPermission Intent intent,
int requestCode,
@Nullable Bundle options)
// 两个参数的
public void startActivityForResult(@RequiresPermission Intent intent,
int requestCode)
其实我们会发现两个参数的方法内部调用的是三个参数的方法,只不过Bundle 对象的值传递了null而已。
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {、
if (mParent == null) {//ActivityGroup mParent。 api 13之前mParent为ActivityGroup类型。api 13以后推荐使用Fragment代替ActivityGroup
// ActivityGroup 最开始被用来在一个界面里嵌套多个activity
options = transferSpringboardActivityOptions(options);
//mMainThread.getApplicationThread() 这个方法返回ApplicationThread类型
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
// TODO Consider clearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
主要看if语句的功能:
1、activitygroup作用及其简单使用可以参考:https://blog.csdn.net/phenixyf/article/details/52066379
2、ApplicationThread是ActivityThread的内部类。这两个类在Activity的启动过程中发挥着重要的作用。
ps:重要方法:mInstrumentation.execStartActivity(源码如下)
1390 public ActivityResult execStartActivity(
1391 Context who, IBinder contextThread, IBinder token, Activity target,
1392 Intent intent, int requestCode, Bundle options) {
1393 IApplicationThread whoThread = (IApplicationThread) contextThread;
1394 if (mActivityMonitors != null) {
1395 synchronized (mSync) {
1396 final int N = mActivityMonitors.size();
1397 for (int i=0; i<N; i++) {
1398 final ActivityMonitor am = mActivityMonitors.get(i);
1399 if (am.match(who, null, intent)) {
1400 am.mHits++;
1401 if (am.isBlocking()) {
1402 return requestCode >= 0 ? am.getResult() : null;
1403 }
1404 break;
1405 }
1406 }
1407 }
1408 }
1409 try {
1410 intent.setAllowFds(false);
1411 intent.migrateExtraStreamToClipData();
//1、真正的启动activity的方法
1412 int result = ActivityManagerNative.getDefault()
1413 .startActivity(whoThread, intent,
1414 intent.resolveTypeIfNeeded(who.getContentResolver()),
1415 token, target != null ? target.mEmbeddedID : null,
1416 requestCode, 0, null, null, options);
//2、检测要启动的activity
1417 checkStartActivityResult(result, intent);
1418 } catch (RemoteException e) {
1419 }
1420 return null;
1421 }
(1)IActivityManager
public interface IActivityManager extends IInterface {
//IInterface 为Binder类型的接口
54 public int startActivity(IApplicationThread caller,
55 Intent intent, String resolvedType, IBinder resultTo, String resultWho,
56 int requestCode, int flags, String profileFile,
57 ParcelFileDescriptor profileFd, Bundle options) throws RemoteException;
...........略
(2) ActivityManagerNative
public abstract class ActivityManagerNative
extends Binder
implements IActivityManager{
/**
* Retrieve the system's default/global activity manager.
*/
static public IActivityManager getDefault() {
return gDefault.get();
}
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;
}
};
}
}
get:
1、ActivityManagerNative 抽象类
2、ActivityManagerNative 是IActivityManager 类型的Binder
延伸:
1、 ActivityManagerService(AMS) 继承自 ActivityManagerNative ,AMS是ActivityManagerNative 的具体实现。
(3)AMS 、ActivityManagerNative 、IActivityManager 关系图
目前综上分析:
1、Activity的启动是ActivityManagerNative.getDefault() 的startActivity()
2、ActivityManagerNative.getDefault()的返回值类型为IActivityManager (接口)
3、AMS是ActivityManagerNative(实现IActivityManager )的实现类
4、ActivityManagerNative为抽象类
得出:ActivityManagerNative实现类AMS来完成activity的启动工作。
(4)checkStartActivityResult(result, intent)
/*package*/ static void checkStartActivityResult(int res, Object intent) {
1610 if (res >= ActivityManager.START_SUCCESS) {
1611 return;
1612 }
1613
1614 switch (res) {
1615 case ActivityManager.START_INTENT_NOT_RESOLVED:
1616 case ActivityManager.START_CLASS_NOT_FOUND:
1617 if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
1618 throw new ActivityNotFoundException(
1619 "Unable to find explicit activity class "
1620 + ((Intent)intent).getComponent().toShortString()
1621 + "; have you declared this activity in your AndroidManifest.xml?");
1622 throw new ActivityNotFoundException(
1623 "No Activity found to handle " + intent);
1624 case ActivityManager.START_PERMISSION_DENIED:
1625 throw new SecurityException("Not allowed to start activity "
1626 + intent);
1627 case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
1628 throw new AndroidRuntimeException(
1629 "FORWARD_RESULT_FLAG used while also requesting a result");
1630 case ActivityManager.START_NOT_ACTIVITY:
1631 throw new IllegalArgumentException(
1632 "PendingIntent is not an activity");
1633 default:
1634 throw new AndroidRuntimeException("Unknown error code "
1635 + res + " when starting " + intent);
1636 }
1637 }
1、开启activity之前要进行检测的
2、上面代码的 :“case ActivityManager.START_CLASS_NOT_FOUND”不正是我们平时可能遇到的吗(AndroidManifest没有注册activity)
通过上文的分析我么知道Activity的开启由ActivityManagerNative的实现类AMS来完成接下来就看下AMS的StartActivity方法(源码如下)
public final class ActivityManagerService extends ActivityManagerNative{
......
//内部调用 startActivityAsUser
public final int startActivity(IApplicationThread caller,
Intent intent,
String resolvedType,
IBinder resultTo,
String resultWho,
int requestCode,
int startFlags,
String profileFile,
ParcelFileDescriptor profileFd,
Bundle options) {
return startActivityAsUser(caller,
intent,
resolvedType,
resultTo,
resultWho,
requestCode,
startFlags,
profileFile,
profileFd,
options,
UserHandle.getCallingUserId()
);
}
public final int startActivityAsUser(IApplicationThread caller,
Intent intent,
String resolvedType,
IBinder resultTo,
String resultWho,
int requestCode,
int startFlags,
String profileFile,
ParcelFileDescriptor profileFd,
Bundle options,
int userId) {
enforceNotIsolatedCaller("startActivity");
userId = handleIncomingUser(Binder.getCallingPid(),
Binder.getCallingUid(),
userId,
false,
true,
"startActivity",
null);
// public ActivityStack mMainStack;
// mMainStack为AMS的属性
return mMainStack.startActivityMayWait(caller,
-1,
intent,
resolvedType,
resultTo,
resultWho,
requestCode,
startFlags,
profileFile,
profileFd,
null,
null,
options,
userId);
}
}
(1)方法调用图解
这样Activity的启动过程转移到了ActivityStack类中的startActivityMayWait,继续看ActivityStack的startActivityMayWait方法
final class ActivityStack {
.........略
//startActivityMayWait方法:
3069 final int startActivityMayWait(IApplicationThread caller, int callingUid,
3070 Intent intent, String resolvedType, IBinder resultTo,
3071 String resultWho, int requestCode, int startFlags, String profileFile,
3072 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3073 Bundle options, int userId) {
...................略
// 内部调用startActivityLocked
3175 int res = startActivityLocked(caller, intent, resolvedType,
3176 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3177 startFlags, options, componentSpecified, null);
3178
3179 if (mConfigWillChange && mMainStack) {
3180 // If the caller also wants to switch to a new configuration,
3181 // do so now. This allows a clean switch, as we are waiting
3182 // for the current activity to pause (so we will not destroy
3183 // it), and have not yet started the next activity.
3184 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3185 "updateConfiguration()");
3186 mConfigWillChange = false;
3187 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3188 "Updating to new configuration after starting activity.");
3189 mService.updateConfigurationLocked(config, null, false, false);
3190 }
3191
...............................略
3223
3224 return res;
3225 }
3226 }
//startActivityLocked方法:
2455 final int startActivityLocked(IApplicationThread caller,
2456 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
2457 String resultWho, int requestCode,
2458 int callingPid, int callingUid, int startFlags, Bundle options,
2459 boolean componentSpecified, ActivityRecord[] outActivity) {
// 内部调用startActivityUncheckedLocked
err = startActivityUncheckedLocked(r, sourceRecord,
2632 startFlags, true, options);
2633 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
2634 // Someone asked to have the keyguard dismissed on the next
2635 // activity start, but we are not actually doing an activity
2636 // switch... just dismiss the keyguard now, because we
2637 // probably want to see whatever is behind it.
2638 mDismissKeyguardOnNextActivity = false;
2639 mService.mWindowManager.dismissKeyguard();
2640 }
2641 return err;
2642 }
}
2654 final int startActivityUncheckedLocked(ActivityRecord r,
2655 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2656 Bundle options) {
.....略
if (!addingToTask && reuseTask == null) {
2869 // We didn't do anything... but it was needed (a.k.a., client
2870 // don't use that intent!) And for paranoia, make
2871 // sure we have correctly resumed the top activity.
2872 if (doResume) {
//内部调用
2873 resumeTopActivityLocked(null, options);
2874 } else {
2875 ActivityOptions.abort(options);
2876 }
2877 return ActivityManager.START_TASK_TO_FRONT;
2878 }
2879 }
2880 }
2881 }
}
方法调用太多直接图解如下:
(1)方法调用图解
(2)重要的realStartActivityLocked方法
// 参数app 重要
final boolean realStartActivityLocked(ActivityRecord r,
616 ProcessRecord app, boolean andResume, boolean checkConfig)
617 throws RemoteException {
xxxx略
// 重要代码
//app.thread的类型为IApplicationThread 类型
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
697 System.identityHashCode(r), r.info,
698 new Configuration(mService.mConfiguration),
699 r.compat, r.icicle, results, newIntents, !andResume,
700 mService.isNextTransitionForward(), profileFile, profileFd,
701 profileAutoStop);
xxxx略
}
app.thread的类型为IApplicationThread 类型
(3)IApplicationThread
/**
40 * System private API for communicating with the application. This is given to
41 * the activity manager by an application when it starts up, for the activity
42 * manager to tell the application about things it needs to do.
43 *
44 * {@hide}
45 */
46 public interface IApplicationThread extends IInterface {
47 void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving,
48 int configChanges) throws RemoteException;
49 void scheduleStopActivity(IBinder token, boolean showWindow,
50 int configChanges) throws RemoteException;
51 void scheduleWindowVisibility(IBinder token, boolean showWindow) throws RemoteException;
52 void scheduleSleeping(IBinder token, boolean sleeping) throws RemoteException;
53 void scheduleResumeActivity(IBinder token, boolean isForward) throws RemoteException;
54 void scheduleSendResult(IBinder token, List<ResultInfo> results) throws RemoteException;
55 void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
56 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
57 Bundle state, List<ResultInfo> pendingResults,
58 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
59 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler)
60 throws RemoteException;
61 void scheduleRelaunchActivity(IBinder token, List<ResultInfo> pendingResults,
62 List<Intent> pendingNewIntents, int configChanges,
63 boolean notResumed, Configuration config) throws RemoteException;
64 void scheduleNewIntent(List<Intent> intent, IBinder token) throws RemoteException;
65 void scheduleDestroyActivity(IBinder token, boolean finished,
66 int configChanges) throws RemoteException;
67 void scheduleReceiver(Intent intent, ActivityInfo info, CompatibilityInfo compatInfo,
68 int resultCode, String data, Bundle extras, boolean sync,
69 int sendingUser) throws RemoteException;
70 static final int BACKUP_MODE_INCREMENTAL = 0;
71 static final int BACKUP_MODE_FULL = 1;
72 static final int BACKUP_MODE_RESTORE = 2;
73 static final int BACKUP_MODE_RESTORE_FULL = 3;
74 void scheduleCreateBackupAgent(ApplicationInfo app, CompatibilityInfo compatInfo,
75 int backupMode) throws RemoteException;
76 void scheduleDestroyBackupAgent(ApplicationInfo app, CompatibilityInfo compatInfo)
77 throws RemoteException;
78 void scheduleCreateService(IBinder token, ServiceInfo info,
79 CompatibilityInfo compatInfo) throws RemoteException;
80 void scheduleBindService(IBinder token,
81 Intent intent, boolean rebind) throws RemoteException;
82 void scheduleUnbindService(IBinder token,
83 Intent intent) throws RemoteException;
84 void scheduleServiceArgs(IBinder token, boolean taskRemoved, int startId,
85 int flags, Intent args) throws RemoteException;
86 void scheduleStopService(IBinder token) throws RemoteException;
87 static final int DEBUG_OFF = 0;
88 static final int DEBUG_ON = 1;
89 static final int DEBUG_WAIT = 2;
90 void bindApplication(String packageName, ApplicationInfo info, List<ProviderInfo> providers,
91 ComponentName testName, String profileName, ParcelFileDescriptor profileFd,
92 boolean autoStopProfiler, Bundle testArguments, IInstrumentationWatcher testWatcher,
93 int debugMode, boolean openGlTrace, boolean restrictedBackupMode, boolean persistent,
94 Configuration config, CompatibilityInfo compatInfo, Map<String, IBinder> services,
95 Bundle coreSettings) throws RemoteException;
96 void scheduleExit() throws RemoteException;
97 void scheduleSuicide() throws RemoteException;
98 void requestThumbnail(IBinder token) throws RemoteException;
99 void scheduleConfigurationChanged(Configuration config) throws RemoteException;
100 void updateTimeZone() throws RemoteException;
101 void clearDnsCache() throws RemoteException;
102 void setHttpProxy(String proxy, String port, String exclList) throws RemoteException;
103 void processInBackground() throws RemoteException;
104 void dumpService(FileDescriptor fd, IBinder servicetoken, String[] args)
105 throws RemoteException;
106 void dumpProvider(FileDescriptor fd, IBinder servicetoken, String[] args)
107 throws RemoteException;
108 void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
109 int resultCode, String data, Bundle extras, boolean ordered,
110 boolean sticky, int sendingUser) throws RemoteException;
111 void scheduleLowMemory() throws RemoteException;
112 void scheduleActivityConfigurationChanged(IBinder token) throws RemoteException;
113 void profilerControl(boolean start, String path, ParcelFileDescriptor fd, int profileType)
114 throws RemoteException;
115 void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd)
116 throws RemoteException;
117 void setSchedulingGroup(int group) throws RemoteException;
118 void getMemoryInfo(Debug.MemoryInfo outInfo) throws RemoteException;
119 static final int PACKAGE_REMOVED = 0;
120 static final int EXTERNAL_STORAGE_UNAVAILABLE = 1;
121 void dispatchPackageBroadcast(int cmd, String[] packages) throws RemoteException;
122 void scheduleCrash(String msg) throws RemoteException;
123 void dumpActivity(FileDescriptor fd, IBinder servicetoken, String prefix, String[] args)
124 throws RemoteException;
125 void setCoreSettings(Bundle coreSettings) throws RemoteException;
126 void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) throws RemoteException;
127 void scheduleTrimMemory(int level) throws RemoteException;
128 Debug.MemoryInfo dumpMemInfo(FileDescriptor fd, boolean checkin, boolean all,
129 String[] args) throws RemoteException;
130 void dumpGfxInfo(FileDescriptor fd, String[] args) throws RemoteException;
131 void dumpDbInfo(FileDescriptor fd, String[] args) throws RemoteException;
132 void unstableProviderDied(IBinder provider) throws RemoteException;
133
134 String descriptor = "android.app.IApplicationThread";
135
136 int SCHEDULE_PAUSE_ACTIVITY_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION;
137 int SCHEDULE_STOP_ACTIVITY_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+2;
...略
/**
* Base class for Binder interfaces. When defining a new interface,
* you must derive it from IInterface.
*/
public interface IInterface
{
/**
* Retrieve the Binder object associated with this interface.
* You must use this instead of a plain cast, so that proxy objects
* can return the correct result.
*/
public IBinder asBinder();
}
get:
1、IApplicationThread 继承了IInterface ()接口,所以IApplicationThread 也是一个Binder接口
2、从IApplicationThread 接口可以看出,其内部包含大量启动停止activity的接口。还有启动停止服务的接口。
3、从接口命名的方式可以猜测IApplicationThread 这个接口是Binder接口的实现者。完成大量和activity、service启动停止相关工作,事实就是这样。
推测:启动、停止相关的工作由谁来完成呢?由于IApplicationThread 是接口,只能由他的实现类来完成。
其实ActivityThread的内部类ApplicationThread就是他的实现类。
(1)ApplicationThread和ApplicationThreadNative
private class ApplicationThread extends ApplicationThreadNative {
...
}
public abstract class ApplicationThreadNative extends Binder implements IApplicationThread {
...
}
由于ApplicationThreadNative 为抽象类,ApplicationThread就是ApplicationThreadNative 的最终实现类。
饶了一大圈得知:Activity的启动是由ApplicationThread的scheduleLaunchActivity方法来启动。
593 // we use token to identify this activity without having to send the
594 // activity itself back to the activity manager. (matters more with ipc)
595 public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
596 ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
597 Bundle state, List<ResultInfo> pendingResults,
598 List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
599 String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
600 ActivityClientRecord r = new ActivityClientRecord();
601
602 r.token = token;
603 r.ident = ident;
604 r.intent = intent;
605 r.activityInfo = info;
606 r.compatInfo = compatInfo;
607 r.state = state;
608
609 r.pendingResults = pendingResults;
610 r.pendingIntents = pendingNewIntents;
611
612 r.startsNotResumed = notResumed;
613 r.isForward = isForward;
614
615 r.profileFile = profileName;
616 r.profileFd = profileFd;
617 r.autoStopProfiler = autoStopProfiler;
618
619 updatePendingConfiguration(curConfig);
620 // 发送一条消息启动Activity的消息,交给Handler 处理(这个Handler有个简洁的名字H)
621 queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
622 }
、、、、、、
private void queueOrSendMessage(int what, Object obj) {
2043 queueOrSendMessage(what, obj, 0, 0);
2044 }
2045
2046 private void queueOrSendMessage(int what, Object obj, int arg1) {
2047 queueOrSendMessage(what, obj, arg1, 0);
2048 }
2049
2050 private void queueOrSendMessage(int what, Object obj, int arg1, int arg2) {
2051 synchronized (this) {
2052 if (DEBUG_MESSAGES) Slog.v(
2053 TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
2054 + ": " + arg1 + " / " + obj);
2055 Message msg = Message.obtain(); //消息封装
2056 msg.what = what;
2057 msg.obj = obj;
2058 msg.arg1 = arg1;
2059 msg.arg2 = arg2;
2060 mH.sendMessage(msg); //最终调用sendMessage发送一条消息
2061 }
2062 }
主要作用:发送一条消息启动Activity的消息,交给Handler 处理(这个Handler有个简洁的名字H)
// ActivityThread 的私有内部类
private class H extends Handler {
1132 public static final int LAUNCH_ACTIVITY = 100;
1133 public static final int PAUSE_ACTIVITY = 101;
1134 public static final int PAUSE_ACTIVITY_FINISHING= 102;
1135 public static final int STOP_ACTIVITY_SHOW = 103;
1136 public static final int STOP_ACTIVITY_HIDE = 104;
1137 public static final int SHOW_WINDOW = 105;
1138 public static final int HIDE_WINDOW = 106;
1139 public static final int RESUME_ACTIVITY = 107;
········略n行
// H 重写了 handler的 消息处理
public void handleMessage(Message msg) {
1226 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
1227 switch (msg.what) {
1228 case LAUNCH_ACTIVITY: {
1229 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
1230 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
1231
1232 r.packageInfo = getPackageInfoNoCheck(
1233 r.activityInfo.applicationInfo, r.compatInfo);
1234 handleLaunchActivity(r, null); // 启动Activity由这个方法实现
1235 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1236 } break;
1237 case RELAUNCH_ACTIVITY: {
1238 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart");
1239 ActivityClientRecord r = (ActivityClientRecord)msg.obj;
1240 handleRelaunchActivity(r);
1241 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1242 } break;
1243 case PAUSE_ACTIVITY:
1244 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
1245 handlePauseActivity((IBinder)msg.obj, false, msg.arg1 != 0, msg.arg2);
1246 maybeSnapshot();
1247 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1248 break;
······略
}
通过“case LAUNCH_ACTIVITY”我们得知Activity的启动由handleLaunchActivity来实现。
······
2228 if (localLOGV) Slog.v(
2229 TAG, "Handling launch of " + r);
2230 Activity a = performLaunchActivity(r, customIntent); // 这里通过performLaunchActivity来完成Activity的创建
2231
2232 if (a != null) {
2233 r.createdConfig = new Configuration(mConfiguration);
2234 Bundle oldState = r.state;
2235 handleResumeActivity(r.token, false, r.isForward,
2236 !r.activity.mFinished && !r.startsNotResumed);
······
get:
1、调用performLaunchActivity 来完成activity对象的创建过程
2、ActivityThread通过handleResumeActivity来调用被启动activity的onResume方法。
2073 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
2074 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
2075 // 1、首先从ActivityInfo 中获取待启动activity的信息
2076 ActivityInfo aInfo = r.activityInfo;
2077 if (r.packageInfo == null) {
2078 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
2079 Context.CONTEXT_INCLUDE_CODE);
2080 }
2081
2082 ComponentName component = r.intent.getComponent();
2083 if (component == null) {
2084 component = r.intent.resolveActivity(
2085 mInitialApplication.getPackageManager());
2086 r.intent.setComponent(component);
2087 }
2088
2089 if (r.activityInfo.targetActivity != null) {
2090 component = new ComponentName(r.activityInfo.packageName,
2091 r.activityInfo.targetActivity);
2092 }
2093
2094 Activity activity = null;
2095 try {
//2、 通过Instrumentation的newActivity方法 通过类加载器创建activity对象
2096 java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
// newActivity的内部封装十分简单,通过类加载器返回一个activity对象
2097 activity = mInstrumentation.newActivity(
2098 cl, component.getClassName(), r.intent);
2099 StrictMode.incrementExpectedActivityCount(activity.getClass());
2100 r.intent.setExtrasClassLoader(cl);
2101 if (r.state != null) {
2102 r.state.setClassLoader(cl);
2103 }
2104 } catch (Exception e) {
2105 if (!mInstrumentation.onException(activity, e)) {
2106 throw new RuntimeException(
2107 "Unable to instantiate activity " + component
2108 + ": " + e.toString(), e);
2109 }
2110 }
2111
2112 try {
// 3、通过LoadedApk 的makeApplication方法创建Application 对象
// LoadedApk packageInfo
2113 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
2114
2115 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
2116 if (localLOGV) Slog.v(
2117 TAG, r + ": app=" + app
2118 + ", appName=" + app.getPackageName()
2119 + ", pkg=" + r.packageInfo.getPackageName()
2120 + ", comp=" + r.intent.getComponent().toShortString()
2121 + ", dir=" + r.packageInfo.getAppDir());
2122
2123 if (activity != null) {
// 4、创建ContextImpl对象,并通过activity的attach方法来完成重要数据的初始化
2124 Context appContext = createBaseContextForActivity(r, activity);
2125 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
2126 Configuration config = new Configuration(mCompatConfiguration);
2127 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
2128 + r.activityInfo.name + " with config " + config);
//通过activity的attach方法来完成重要数据的初始化
2129 activity.attach(appContext, this, getInstrumentation(), r.token,
2130 r.ident, app, r.intent, r.activityInfo, title, r.parent,
2131 r.embeddedID, r.lastNonConfigurationInstances, config);
2132
2133 if (customIntent != null) {
2134 activity.mIntent = customIntent;
2135 }
2136 r.lastNonConfigurationInstances = null;
2137 activity.mStartedActivity = false;
2138 int theme = r.activityInfo.getThemeResource();
2139 if (theme != 0) {
2140 activity.setTheme(theme);
2141 }
2142
2143 activity.mCalled = false;
// 5、通过Instrumentation的callActivityOnCreate调用activity的onCreate方法
2144 mInstrumentation.callActivityOnCreate(activity, r.state);
2145 if (!activity.mCalled) {
2146 throw new SuperNotCalledException(
2147 "Activity " + r.intent.getComponent().toShortString() +
2148 " did not call through to super.onCreate()");
2149 }
2150 r.activity = activity;
2151 r.stopped = true;
2152 if (!r.activity.mFinished) {
2153 activity.performStart();
2154 r.stopped = false;
2155 }
2156 if (!r.activity.mFinished) {
2157 if (r.state != null) {
2158 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2159 }
2160 }
2161 if (!r.activity.mFinished) {
2162 activity.mCalled = false;
2163 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2164 if (!activity.mCalled) {
2165 throw new SuperNotCalledException(
2166 "Activity " + r.intent.getComponent().toShortString() +
2167 " did not call through to super.onPostCreate()");
2168 }
2169 }
2170 }
2171 r.paused = true;
2172
2173 mActivities.put(r.token, r);
2174
2175 } catch (SuperNotCalledException e) {
2176 throw e;
2177
2178 } catch (Exception e) {
2179 if (!mInstrumentation.onException(activity, e)) {
2180 throw new RuntimeException(
2181 "Unable to start activity " + component
2182 + ": " + e.toString(), e);
2183 }
2184 }
2185
2186 return activity;
2187 }
收获:
1、首先从ActivityInfo 中获取待启动activity的信息
2、通过Instrumentation的newActivity方法 通过类加载器创建activity对象
3、通过LoadedApk 的makeApplication方法创建Application 对象(makeApplication源码略,可以参考在线源码)a、从makeApplication源码中可以知道:application只会创建一次,意味着整个应用中只有一个Application对象
b、application对象的创建也是通过Instrumentation来完成的,也是通过类加载器来完成(和activity类似)
c、application对象创建后系统通过调用Instrumentation的callAppApplicationOnCreate方法来调用application的onCreate4、创建ContextImpl对象,并通过activity的attach方法来完成重要数据的初始化
a、ContextImpl是一个重要的数据结构,他是Context的具体实现。Context的大部分逻辑都是ContextImpl来完成的。
b、ContextImpl通过activity的attach方法和activity建立关联
c、attach方法中activity还会完成window的创建,并建立自己和window的关联。这样window接收到的外部事件就可以传递给activity5、通过Instrumentation的callActivityOnCreate调用activity的onCreate方法
ps:上文源码中已经添加注释
一周啦,断断续续总结了一遍,自己很多也很懵逼,但是发现知识慢慢的都有了联系,好像要跨过瓶颈渡劫的感觉哈哈哈!继续积累,硬着头皮接着搞。吧知识先过一遍吧,留个印象。。。溜溜球!!!!!
声明:本文读《 安卓开发艺术探索 》所做笔记。
付:
源码来自安卓系统4.2.2在线源码
使用参考