android serialport new 软件退出_基于Android9.0,了解Android启动流程
先記住四個進程和三種方式。
**四個進程**
1.Launcher進程
2.system_server進程
3.App進程
4.Zygote進程
**三種方式**
1.Binder方式
2.Socket方式
3.Handler方式
點擊桌面APP圖標,Launcher調用startActivitySafely(Launcher進程)
```java
/**
* Default launcher application.
*/
public final class Launcher extends Activity
implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
View.OnTouchListener {
....
/**
* Launches the intent referred by the clicked shortcut.
*
* @param v The view representing the clicked shortcut.
*/
public void onClick(View v) {
// Make sure that rogue clicks don't get through while allapps is launching, or after the
// view has detached (it's possible for this to happen if the view is removed mid touch).
...
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()));
boolean success = startActivitySafely(v, intent, tag);//注意這里
if (success && v instanceof BubbleTextView) {
mWaitingForResume = (BubbleTextView) v;
mWaitingForResume.setStayPressed(true);
}
} else if (tag instanceof FolderInfo) {
...
} else if (v == mAllAppsButton) {
...
}
}
```
```java
boolean startActivitySafely(View v, Intent intent, Object tag) {
boolean success = false;
try {
success = startActivity(v, intent, tag);//注意這里
} catch (ActivityNotFoundException e) {
...
}
return success;
}
```
接著看startActivity
```java
boolean startActivity(View v, Intent intent, Object tag) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//這里表示要在新的task中啟動activity
try {
// Only launch using the new animation if the shortcut has not opted out (this is a
// private contract between launcher and may be ignored in the future).
//只有在快捷方式沒有選擇退出時才使用新動畫啟動(這是一個
//私有合同之間的啟動和可能被忽略在未來)。//這是有道翻譯的
//如果快捷方式尚未退出,則僅使用新動畫啟動(這是
//啟動器之間的私人合同,將來可能會被忽略)。//這是google翻譯的
//大概知道什么意思就行,不必糾結有道還是google
boolean useLaunchAnimation = (v != null) &&
!intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
UserHandle user = (UserHandle) intent.getParcelableExtra(ApplicationInfo.EXTRA_PROFILE);
LauncherApps launcherApps = (LauncherApps)
this.getSystemService(Context.LAUNCHER_APPS_SERVICE);
if (useLaunchAnimation) {
ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
v.getMeasuredWidth(), v.getMeasuredHeight());
if (user == null || user.equals(android.os.Process.myUserHandle())) {
// Could be launching some bookkeeping activity
startActivity(intent, opts.toBundle());//注意這里
} else {
launcherApps.startMainActivity(intent.getComponent(), user,
intent.getSourceBounds(),
opts.toBundle());
}
} else {
...
}
return true;
} catch (SecurityException e) {
...
}
return false;
}
```
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
表示要在一個新的Task(任務棧)中啟動這個Activity
Android系統中的每一個Activity都位于一個Task中,一個Task可以包含多個Activity,同一個Activity也可能有多個實例。 在AndroidManifest.xml中,我們可以通過android:launchMode來控制Activity在Task中的實例。
在startActivity的時候,我們也可以通過setFlag 來控制啟動的Activity在Task中的實例。
在Task之外,還有一層容器,這個容器應用開發者和用戶可能都不會感覺到或者用到,但它卻非常重要,那就是Stack,Android系統中的多窗口管理,就是建立在Stack的數據結構上的。 一個Stack中包含了多個Task,一個Task中包含了多個Activity(Window)。
Launcher進程采用Binder向system_server進程發起startActivity請求,現在我們從最熟悉的startAcitivty開始分析(養成先有點,再有線,最后成面的思路,防止看完懵逼)。startActivity有好幾種重載方式,跟源碼一層一層跟下去,發現最后都會調用startActivityForResult。
```java
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
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());
}
...
} else {
...
}
}
```
我們這里關注mParent == null條件的即可,mParent 代表的是ActivityGroup,ActivityGroup最開始被用來在一個界面中嵌入多個子Activity,但是在API13中已經被廢棄了,系統推薦采用 Fragment來代替ActivityGroup。
繼續跟下去,查看mInstrumentation.execStartActivity,mInstrumentation是Instrumentation的實例,Instrumentation擁有跟蹤application及activity的功能。
```java
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...
try {
...
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);//注意這里
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
...
}
return null;
}
```
最后調用
ActivityManager.getService().startActivity來完成啟動。
點進ActivityManager.getService()查看
```java
/**
* @hide
*/
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
```
發現是一個IActivityManager的單例。
IActivityManager是一個Binder接口,而ActivityManagerService(AMS)繼承IActivityManager.Stub,IActivityManager.Stub是IActivityManager.aidl生成的接口類,Android8.0開始,把一些Binder代碼轉化為了AIDL模板方式。這里生成一個Launcher進程的AMS代理,AMS是IActivityManager的具體實現,所以這里,就需要去看AMS的startActivity方法。(在system_server進程中調用)
```java
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
boolean validateIncomingUser) {
enforceNotIsolatedCaller("startActivity");
userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
// TODO: Switch to user app stacks here.
return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();
}
```
mActivityStartController是ActivityStartController的實例
```java
/**
* @return A starter to configure and execute starting an activity. It is valid until after
* {@link ActivityStarter#execute} is invoked. At that point, the starter should be
* considered invalid and no longer modified or used.
*/
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
```
mFactory是ActivityStarter的一個內部接口,我們再來看看ActivityStarter的execute方法
```java
/**
* Starts an activity based on the request parameters provided earlier.
* @return The starter result.
*/
int execute() {
try {
// TODO(b/64750076): Look into passing request directly to these methods to allow
// for transactional diffs and preprocessing.
if (mRequest.mayWait) {
return startActivityMayWait(mRequest.caller, mRequest.callingUid,
...
} else {
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
...
}
} finally {
...
}
}
```
因為之前調用了ActivityStarter的setMayWait方法
```java
ActivityStarter setMayWait(int userId) {
mRequest.mayWait = true;
mRequest.userId = userId;
return this;
}
```
所以,這里的mRequest.mayWait為true,繼續跟
```java
private int startActivityMayWait(IApplicationThread caller, int callingUid,
String callingPackage, Intent intent, String resolvedType,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, WaitResult outResult,
Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
int userId, TaskRecord inTask, String reason,
boolean allowPendingRemoteAnimationRegistryLookup) {
...
final ActivityRecord[] outRecord = new ActivityRecord[1];
int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
allowPendingRemoteAnimationRegistryLookup);
Binder.restoreCallingIdentity(origId);
...
return res;
}
}
```
接著,連進三個startActivity的重載方法,然后到startActivityUnchecked,后面一串調用startActivityUnchecked->ActivityStackSupervisor.resumeFocusedStackTopActivityLocked->ActivityStack.resumeTopActivityUncheckedLocked->ActivityStack.resumeTopActivityUncheckedLocked->ActivityStack.resumeTopActivityInnerLocked->ActivityStackSupervisor.startSpecificActivityLocked
```java
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// 該活動的應用程序是否已經在運行?
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
getLaunchTimeTracker().setLaunchTime(r);
if (app != null && app.thread != null) {//ProcessRecord類型的對象記錄了進程相關的信息,app.thread為IApplicationThread,這兩個對象在進程為創建時,都是為null的
try {
...
realStartActivityLocked(r, app, andResume, checkConfig);//熱啟動走向,注意這里,進入分支二
return;
} catch (RemoteException e) {
...
}
// If a dead object exception was thrown -- fall through to
// restart the application.
}
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);//冷啟動走向,注意這里,進入分支一
}
```
---
### 分支一:進程還沒有創建
ActivityManagerService.startProcessLocked
```java
@GuardedBy("this")
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
String hostingType, ComponentName hostingName, boolean allowWhileBooting,
boolean isolated, boolean keepIfLarge) {
return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
null /* crashHandler */);//這里以socket的方式,進行跨進程通信。通知zygote fork出app進程
}
@GuardedBy("this")
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
long startTime = SystemClock.elapsedRealtime();
ProcessRecord app;
if (!isolated) {//這里為false
app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
checkTime(startTime, "startProcess: after getProcessRecord");
...
} else {
// If this is an isolated process, it can't re-use an existing process.
//如果這是一個獨立的進程,它就不能重用現有的進程。
app = null;
}
...
if (app == null) {
checkTime(startTime, "startProcess: creating new process record");
app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
//創建并鎖定
...
} else {
// If this is a new package in the process, add the package to the list
...
}
...
checkTime(startTime, "startProcess: stepping in to startProcess");
final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);//注意這里
checkTime(startTime, "startProcess: done starting proc!");
return success ? app : null;
}
```
進入startProcessLocked
```java
@GuardedBy("this")
private final boolean startProcessLocked(ProcessRecord app,
String hostingType, String hostingNameStr, String abiOverride) {
return startProcessLocked(app, hostingType, hostingNameStr,
false /* disableHiddenApiChecks */, abiOverride);
}
/**
* @return {@code true} if process start is successful, false otherwise.
*/
@GuardedBy("this")
private final boolean startProcessLocked(ProcessRecord app, String hostingType,
String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
...
return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
startTime);//注意這里
} catch (RuntimeException e) {
...
return false;
}
}
@GuardedBy("this")
private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
app.pendingStart = true;
app.killedByAm = false;
app.removed = false;
app.killed = false;
final long startSeq = app.startSeq = ++mProcStartSeqCounter;
app.setStartParams(uid, hostingType, hostingNameStr, seInfo, startTime);
if (mConstants.FLAG_PROCESS_START_ASYNC) {
...
final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,
requiredAbi, instructionSet, invokeWith, app.startTime);//注意這里
synchronized (ActivityManagerService.this) {
handleProcessStartedLocked(app, startResult, startSeq);
}
...
});
return true;
} else {
...
final ProcessStartResult startResult = startProcess(hostingType, entryPoint, app,
uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
invokeWith, startTime);//注意這里
handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
startSeq, false);
...
return app.pid > 0;
}
}
```
繼續看startProcess
```java
private ProcessStartResult startProcess(String hostingType, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
...
if (hostingType.equals("webview_service")) {
...
} else {
startResult = Process.start(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, invokeWith,
new String[] {PROC_START_SEQ_IDENT + app.startSeq});
}
...
return startResult;
...
}
```
繼續看Process.start
```java
public static final ProcessStartResult start(final String processClass,
final String niceName,
int uid, int gid, int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String abi,
String instructionSet,
String appDataDir,
String invokeWith,
String[] zygoteArgs) {
return zygoteProcess.start(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
}
```
zygoteProcess為ZygoteProcess實例,繼續看ZygoteProcess的start
```java
public final Process.ProcessStartResult start(final String processClass,
...{
try {
return startViaZygote(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, false /* startChildZygote */,
zygoteArgs);
} catch (ZygoteStartFailedEx ex) {
...
}
}
```
繼續
```java
private Process.ProcessStartResult startViaZygote(final String processClass,
...
synchronized(mLock) {
return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);//注意這里,以及注意openZygoteSocketIfNeeded這個方法
}
}
```
繼續
```java
@GuardedBy("mLock")
private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
ZygoteState zygoteState, ArrayList<String> args)
throws ZygoteStartFailedEx {
...
// Should there be a timeout on this?
Process.ProcessStartResult result = new Process.ProcessStartResult();//注意這里
...
return result;
} catch (IOException ex) {
...
}
}
```
這里的openZygoteSocketIfNeeded(),內部實現Zygote通過Socket的方式,與system_sever連接,最后調用native層方法nativeForkAndSpecialize,fork一個新的進程。(這條線,自行閱讀、跟蹤源碼。記住:點成線,線成面,切勿貪心,否則一臉懵逼。)
至此APP進程創建完成,接著會通過反射執行APP進程的ActivityThread的main方法,這個main方法是APP進程的入口。
```java
public static void main(String[] args) {
...
Looper.prepareMainLooper();//創建一個主線程的Looper
...
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);//注意這里
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
...
Looper.loop();//開啟循環
throw new RuntimeException("Main thread loop unexpectedly exited");
}
```
繼續看attach
```java
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
...
final IActivityManager mgr = ActivityManager.getService();//獲取AMS在app客戶端的代理對象
try {
mgr.attachApplication(mAppThread, startSeq);//注意這里,app進程掛起,執行system進程AMS的attachApplication
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
...
}
```
繼續attachApplication
```java
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
...
attachApplicationLocked(thread, callingPid, callingUid, startSeq);//注意這里
...
}
}
```
繼續attachApplicationLocked
```java
@GuardedBy("this")
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
...
if (app.isolatedEntryPoint != null) {
// This is an isolated process which should just call an entry point instead of
// being bound to an application.
thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
} else if (app.instr != null) {
thread.bindApplication(processName, appInfo, providers,
app.instr.mClass,
profilerInfo, app.instr.mArguments,
app.instr.mWatcher,
app.instr.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);
} else {
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled);
}
...
} catch (Exception e) {
...
}
// See if the top visible activity is waiting to run in this process...
//看看頂部可見的活動是否正在等待在這個進程中運行……
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {//注意這里
didSomething = true;
}
} catch (Exception e) {
..
}
}
...
return true;
}
```
thread為IApplicationThread,這里system進程調用app進程的ActivityThrad.ApplicationThread的bindApplication,同時
繼續看看
```java
public final void bindApplication(String processName, ApplicationInfo appInfo,
List<ProviderInfo> providers, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial, boolean autofillCompatibilityEnabled) {
...
sendMessage(H.BIND_APPLICATION, data);
}
```
局勢越來越明朗了,繼續sendMessage,連著幾個重載,最后到H的H.BIND_APPLICATION
```java
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);//注意這里
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
```
繼續handleBindApplication
```java
private void handleBindApplication(AppBindData data) {
...
final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
appContext.getClassLoader(), false, true, false);//拿到并保存了ApplicationInfo所包含的代碼和資源的目錄
final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);//創建要啟動Activity的上下文環境
try {
final ClassLoader cl = instrContext.getClassLoader();
mInstrumentation = (Instrumentation)
cl.loadClass(data.instrumentationName.getClassName()).newInstance();//用類加載器來創建Instrumentation實例
} catch (Exception e) {
...
}
final ComponentName component = new ComponentName(ii.packageName, ii.name);//該類保存了Activity類名和包名
mInstrumentation.init(this, instrContext, appContext, component,
data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
...
} else {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
}
app = data.info.makeApplication(data.restrictedBackupMode, null);//這里生成Application
...
try {
mInstrumentation.callApplicationOnCreate(app);//注意這里
} catch (Exception e) {
...
}
} finally {
...
}
...
}
```
繼續
```java
public void callApplicationOnCreate(Application app) {
app.onCreate();//執行Application的onCreate()方法
}
```
這里Application由data.info.makeApplication生成,http://data.info為LoadedApk對象,所以這里看LoadedApk的makeApplication
```java
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
...
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
...
}
mActivityThread.mAllApplications.add(app);
mApplication = app;
if (instrumentation != null) {//這里傳入的instrumentation為null,data.info.makeApplication(data.restrictedBackupMode, null);
try {
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
...
}
}
...
return app;
}
```
記得attachApplicationLocked里面,還調用了ActivityStackSupervisor的attachApplicationLocked
```java
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
final String processName = app.processName;
...
if (realStartActivityLocked(activity, app,
top == activity /* andResume */, true /* checkConfig */)) {//注意這里
didSomething = true;
}
} catch (RemoteException e) {
...
}
}...
return didSomething;
}
```
繼續看realStartActivityLocked,的后面接著下面的**分支二**
### 分支二:進程已經創建
ActivityStackSupervisor.realStartActivityLocked
```java
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
...
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.執行Activity啟動事務
mService.getLifecycleManager().scheduleTransaction(clientTransaction);//注意這里
...
return true;
}
```
mService是AMS,getLifecycleManager()返回一個ClientLifecycleManager對象
```java
/**
* Schedule a transaction, which may consist of multiple callbacks and a lifecycle request.
* @param transaction A sequence of client transaction items.
* @throws RemoteException
*
* @see ClientTransaction
*/
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
// If client is not an instance of Binder - it's a remote call and at this point it is
// safe to recycle the object. All objects used for local calls will be recycled after
// the transaction is executed on client in ActivityThread.
transaction.recycle();
}
}
```
scheduleTransaction內部調用ClientTransaction.schedule
```java
/**
* Schedule the transaction after it was initialized. It will be send to client and all its
* individual parts will be applied in the following sequence:
* 1. The client calls {@link #preExecute(ClientTransactionHandler)}, which triggers all work
* that needs to be done before actually scheduling the transaction for callbacks and
* lifecycle state request.
* 2. The transaction message is scheduled.
* 3. The client calls {@link TransactionExecutor#execute(ClientTransaction)}, which executes
* all callbacks and necessary lifecycle transitions.
*/
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
```
這里mClient就是執行ClientTransaction.obtain(app.thread,r.appToken);時,傳進來的app.thread,也就是IApplicationThread。
```java
/** Obtain an instance initialized with provided params. */
public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
if (instance == null) {
instance = new ClientTransaction();
}
instance.mClient = client;
instance.mActivityToken = activityToken;
return instance;
}
```
IApplicationThread的具體實現為ActivityThread的內部類ApplicationThread,兜兜轉轉,又回到了ApplicationThread
```java
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
```
ActivityThread的內部沒有scheduleTransaction()方法,看父類的ClientTransactionHandler
```java
/** Prepare and schedule transaction for execution. */
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
```
ClientTransactionHandler的sendMessage是一個抽象方法,所以去實現類ActivityThread去找,最終調用ActivityThread的sendMessage方法
```java
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
if (DEBUG_MESSAGES) Slog.v(
TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
+ ": " + arg1 + " / " + obj);
Message msg = Message.obtain();
msg.what = what;//ActivityThread.H.EXECUTE_TRANSACTION
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
```
mH是Handler的實例,繼續跟mH的EXECUTE_TRANSACTION
```java
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem()) {
// Client transactions inside system process are recycled on the client side
// instead of ClientLifecycleManager to avoid being cleared before this
// message is handled.
transaction.recycle();
}
// TODO(lifecycler): Recycle locally scheduled transactions.
break;
```
mTransactionExecutor為TransactionExecutor的實例,繼續
```java
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
log("End resolving transaction");
}
```
調用了executeCallbacks和executeLifecycleState,繼續
```java
/** Cycle through all states requested by callbacks and execute them at proper times. */
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
...
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
log("Resolving callback: " + item);
final int postExecutionState = item.getPostExecutionState();
final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
item.getPostExecutionState());
if (closestPreExecutionState != UNDEFINED) {
cycleToPath(r, closestPreExecutionState);
}
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
if (r == null) {
// Launch activity request will create an activity record.
r = mTransactionHandler.getActivityClient(token);
}
if (postExecutionState != UNDEFINED && r != null) {
// Skip the very last transition and perform it by explicit state request instead.
final boolean shouldExcludeLastTransition =
i == lastCallbackRequestingState && finalState == postExecutionState;
cycleToPath(r, postExecutionState, shouldExcludeLastTransition);
}
}
}
/** Transition to the final state if requested by the transaction. */
private void executeLifecycleState(ClientTransaction transaction) {
...
// Cycle to the state right before the final requested state.
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
```
executeCallbacks和executeLifecycleState都調用了cycleToPath,繼續
```java
/** Transition the client between states. */
@VisibleForTesting
public void cycleToPath(ActivityClientRecord r, int finish) {
cycleToPath(r, finish, false /* excludeLastState */);
}
/**
* Transition the client between states with an option not to perform the last hop in the
* sequence. This is used when resolving lifecycle state request, when the last transition must
* be performed with some specific parameters.
*/
private void cycleToPath(ActivityClientRecord r, int finish,
boolean excludeLastState) {
final int start = r.getLifecycleState();
log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
performLifecycleSequence(r, path);//注意這里
}
```
繼續跟進performLifecycleSequence
```java
/** Transition the client through previously initialized state sequence. */
private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
final int size = path.size();
for (int i = 0, state; i < size; i++) {
state = path.get(i);
log("Transitioning to state: " + state);
switch (state) {
case ON_CREATE://注意這里
mTransactionHandler.handleLaunchActivity(r, mPendingActions,
null /* customIntent */);
break;
case ON_START:
mTransactionHandler.handleStartActivity(r, mPendingActions);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
false /* userLeaving */, 0 /* configChanges */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r.token, false /* show */,
0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r.token, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
}
```
mTransactionHandler為傳入的ClientTransactionHandler,其handleLaunchActivity為抽象方法,其子類ActivityThread實現了該方法
```java
/**
* Extended implementation of activity launch. Used when server requests a launch or relaunch.
*/
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
...
final Activity a = performLaunchActivity(r, customIntent);
...
return a;
}
```
繼續performLaunchActivity
```java
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;//獲取ActivityInfo類
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);// 獲取APK文件描述LoadedApk,LoadedApk在構造時,拿到并保存了ApplicationInfo所包含的代碼和資源的目錄
}
ComponentName component = r.intent.getComponent();//獲取要啟動的Activity的ComponentName類,該類保存了Activity類名和包名
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);
}
ContextImpl appContext = createBaseContextForActivity(r);// 創建要啟動Activity的上下文環境
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();// 用類加載器來創建Activity實例
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
...
} catch (Exception e) {
...
}
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);// 創建Application,makeApplication方法內部會調用創建Application的onCreate()
...
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback);// 初始化Activity,在attach方法中會創建window對象并與Activity關聯
...
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...
}
...
} catch (SuperNotCalledException e) {
...
} catch (Exception e) {
...
}
return activity;
}
```
r.isPersistable()
```java
public boolean isPersistable() {
return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
}
```
繼續走Instrumentation的callActivityOnCreate(activity, r.state, r.persistentState);
```java
/**
* Perform calling of an activity's {@link Activity#onCreate}
* method. The default implementation simply calls through to that method.
* @param activity The activity being created.
* @param icicle The previously frozen state (or null) to pass through to
* @param persistentState The previously persisted state (or null)
*/
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);//注意這里
postPerformCreate(activity);
}
```
繼續,Activity.performCreate
```java
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
mCanEnterPictureInPicture = true;
restoreHasCurrentPermissionRequest(icicle);
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
mActivityTransitionState.readState(icicle);
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mFragments.dispatchActivityCreated();
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}
```
終于看到了熟悉的onCreate,感動,Read The Fucking Source Code。
---
### 總結:
- 先弄清楚,APP的啟動流程。至于流程中涉及的Binder、Socket、Handler、反射等,后續再慢慢展開學習、了解
- 胖子有什么理解錯誤的,歡迎大家指出來,一起討論、學習、進步
- 胖子文筆不怎么好,第一次寫博客,盡量一次走一條路,岔路后續再慢慢補齊
- 寫博客,對了解、學習、加深源碼內部機制,有很大的幫助
- 期待胖子的第二篇[《Android消息機制》](基于Android9.0,了解Android消息機制)
---
### 參考文獻
[Android 9.0 點擊桌面應用圖標,啟動Activity的過程分析](CSDN-個人空間)
[android點擊桌面App圖標activity啟動流程](Android啟動過程 - 左手指月 - 博客園)
Android開發藝術探索<br/>
總結
以上是生活随笔為你收集整理的android serialport new 软件退出_基于Android9.0,了解Android启动流程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 民生visa全币种信用卡额度一般是多少
- 下一篇: 《饥饿游戏》前传女主演敲定:“白雪公主”