当前位置: 首页 > news >正文

个人网站备案能做什么内容科技与狠活是什么梗

个人网站备案能做什么内容,科技与狠活是什么梗,最好用的短链接生成器,国外建筑公司网站先记住四个进程和三种方式。**四个进程**1.Launcher进程2.system_server进程3.App进程4.Zygote进程**三种方式**1.Binder方式2.Socket方式3.Handler方式点击桌面APP图标#xff0c;Launcher调用startActivitySafely#xff08;Launcher进程#xff09;java/*** Default laun…先记住四个进程和三种方式。**四个进程**1.Launcher进程2.system_server进程3.App进程4.Zygote进程**三种方式**1.Binder方式2.Socket方式3.Handler方式点击桌面APP图标Launcher调用startActivitySafelyLauncher进程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 dont get through while allapps is launching, or after the // view has detached (its 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; }接着看startActivityjavaboolean 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(任务栈)中启动这个ActivityAndroid系统中的每一个Activity都位于一个Task中,一个Task可以包含多个Activity同一个Activity也可能有多个实例。 在AndroidManifest.xml中我们可以通过android:launchMode来控制Activity在Task中的实例。在startActivity的时候我们也可以通过setFlag 来控制启动的Activity在Task中的实例。在Task之外还有一层容器这个容器应用开发者和用户可能都不会感觉到或者用到但它却非常重要那就是StackAndroid系统中的多窗口管理就是建立在Stack的数据结构上的。 一个Stack中包含了多个Task一个Task中包含了多个ActivityWindow)。Launcher进程采用Binder向system_server进程发起startActivity请求现在我们从最熟悉的startAcitivty开始分析养成先有点再有线最后成面的思路防止看完懵逼。startActivity有好几种重载方式跟源码一层一层跟下去发现最后都会调用startActivityForResult。javapublic 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 代表的是ActivityGroupActivityGroup最开始被用来在一个界面中嵌入多个子Activity但是在API13中已经被废弃了系统推荐采用 Fragment来代替ActivityGroup。继续跟下去查看mInstrumentation.execStartActivitymInstrumentation是Instrumentation的实例Instrumentation拥有跟踪application及activity的功能。javapublic 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 SingletonIActivityManager IActivityManagerSingleton new SingletonIActivityManager() { Override protected IActivityManager create() { final IBinder b ServiceManager.getService(Context.ACTIVITY_SERVICE); final IActivityManager am IActivityManager.Stub.asInterface(b); return am; } };发现是一个IActivityManager的单例。 IActivityManager是一个Binder接口而ActivityManagerServiceAMS继承IActivityManager.StubIActivityManager.Stub是IActivityManager.aidl生成的接口类Android8.0开始把一些Binder代码转化为了AIDL模板方式。这里生成一个Launcher进程的AMS代理AMS是IActivityManager的具体实现所以这里就需要去看AMS的startActivity方法。在system_server进程中调用javaOverride 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方法javaActivityStarter setMayWait(int userId) { mRequest.mayWait true; mRequest.userId userId; return this; }所以这里的mRequest.mayWait为true继续跟javaprivate 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.startSpecificActivityLockedjavavoid 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.startProcessLockedjavaGuardedBy(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 cant 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;}进入startProcessLockedjavaGuardedBy(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; } }继续看startProcessjavaprivate 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.startjavapublic 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的startjavapublic 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) { ... }}继续javaprivate Process.ProcessStartResult startViaZygote(final String processClass, ... synchronized(mLock) { return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);//注意这里,以及注意openZygoteSocketIfNeeded这个方法 }}继续javaGuardedBy(mLock)private static Process.ProcessStartResult zygoteSendArgsAndGetResult( ZygoteState zygoteState, ArrayListString 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层方法nativeForkAndSpecializefork一个新的进程。这条线自行阅读、跟踪源码。记住点成线线成面切勿贪心否则一脸懵逼。至此APP进程创建完成接着会通过反射执行APP进程的ActivityThread的main方法这个main方法是APP进程的入口。javapublic 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);}继续看attachjavaprivate 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(); } ...}继续attachApplicationjavaOverridepublic final void attachApplication(IApplicationThread thread, long startSeq) { synchronized (this) { ... attachApplicationLocked(thread, callingPid, callingUid, startSeq);//注意这里 ... }}继续attachApplicationLockedjavaGuardedBy(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同时继续看看javapublic final void bindApplication(String processName, ApplicationInfo appInfo, ListProviderInfo 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_APPLICATIONjavacase 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;继续handleBindApplicationjavaprivate 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 { ... } ...}继续javapublic void callApplicationOnCreate(Application app) { app.onCreate();//执行Application的onCreate()方法}这里Application由data.info.makeApplication生成http://data.info为LoadedApk对象所以这里看LoadedApk的makeApplicationjavapublic 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为nulldata.info.makeApplication(data.restrictedBackupMode, null); try { instrumentation.callApplicationOnCreate(app); } catch (Exception e) { ... } }... return app;}记得attachApplicationLocked里面还调用了ActivityStackSupervisor的attachApplicationLockedjavaboolean 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.realStartActivityLockedjavafinal 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是AMSgetLifecycleManager()返回一个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 - its 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.schedulejava/** * 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兜兜转转又回到了ApplicationThreadjavaOverridepublic void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ActivityThread.this.scheduleTransaction(transaction);}ActivityThread的内部没有scheduleTransaction()方法看父类的ClientTransactionHandlerjava/** Prepare and schedule transaction for execution. */ void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); }ClientTransactionHandler的sendMessage是一个抽象方法所以去实现类ActivityThread去找最终调用ActivityThread的sendMessage方法javaprivate 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_TRANSACTIONjavacase 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的实例继续javapublic 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);//注意这里 }继续跟进performLifecycleSequencejava/** 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; }继续performLaunchActivityjava/** 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文件描述LoadedApkLoadedApk在构造时拿到并保存了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()javapublic boolean isPersistable() { return activityInfo.persistableMode ActivityInfo.PERSIST_ACROSS_REBOOTS;}继续走Instrumentation的callActivityOnCreate(activity, r.state, r.persistentState);java/** * Perform calling of an activitys {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.performCreatejavafinal 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/
http://www.yutouwan.com/news/403448/

相关文章:

  • 中国建设职业注册中心网站免费网站平台推荐
  • 上海网站建设网页制作怎么样周口网站建设 网站制作 网络推广
  • 南宁网站制作开发公司泰安千橙网站建设优化熊掌号
  • 做便宜网站珠海网站建设制作
  • 查询网站流量的网址微网站域名
  • 做外单网站有哪些建设银行啦卡信用网站
  • 和男人人做的网站深圳建网站三千
  • 思政网站建设管理自查报告学历提升快速拿证
  • 有没有专门做橱窗的案例网站网站制作 徐州
  • 设计网站的一般过程网站中链接怎么做
  • 如何建设社交网站wordpress安装主题后不够
  • 网站建设调研论文阿里云有了域名 网站建设
  • 商会网站设计网站策划ps
  • 班级网站网页设计做图表好看的网站
  • 怎样在网站上做免费的推广wordpress开发文档下载
  • 坪地网站制作网站手机网站制作
  • 什么网站可以免费做视频it运维培训
  • 国外设计文章的网站网站宣传册怎么做的
  • 辽宁注册公司网站企业网站建设应注意什么
  • 宁波建设协会网站关键词优化是什么意思
  • 公司做网站的费用怎么账务处理智通人才网东莞最新招聘信息官网
  • 安徽静安集团网站建设深圳网站建设公司 概况
  • 宁波网站建设哪家比较好怎么在网上卖东西视频
  • 网站建设十大公司临河网站建设
  • 大连网站制作团队高校网站建设说明书
  • 无锡个人网站建设世界十大著名室内设计师
  • 在线报名网站建设如何建立设计一个公司网站
  • 知名做网站哪家好摄影网站模版
  • 怎样使用仿站小工具做网站ppt模板大全百度云
  • 微信网站是怎么做的高密市住房和城乡建设局网站