Android應用啓動中的進程交互

應用啓動中的進程交互

關於進程


關於Android中的進程,有必要知道:java

  • 每一個App都運行在單獨的應用進程中
  • 除了應用進程,系統還有Init進程,Zygote進程,SystemServer進程,這些系統進程都是在Android系統啓動時產生的。
    • Init進程是Android系統的第一個進程。Init進程建立了Zygote進程,
    • Zygote進程經過fork()方式建立其餘進程,包括SystemServer進程和應用進程。
    • SytemServer進程,即系統服務進程,咱們App能擁有framework的能力都是它提供的。好比Activity的啓動就是經過系統服務進程中的ActivityManagerService。
  • apk(dex)文件的運行環境是DalvikVM,也稱之爲ART(Android Runtime) 。Zygote進程建立了最初的VM。每一個進程中都有一個VM。Zygote fork的應用進程天然也擁有本身的VM。

截屏2020-10-16下午4.45.57.png

進程啓動概覽

Android應用程序啓動過程源代碼分析 這篇文章詳細描述了這個過程。
下面涉及到的源碼爲Android7.0。AOSP git分支:nougat-release


截屏2020-10-16下午5.03.37.pngandroid

1.Activity.startActivity

隱式啓動

咱們以應用A隱式啓動應用B的Activity爲例,介紹應用啓動過程當中的進程交互。
咱們有兩個App,這樣應用A就能夠經過Intent("com.a.appb.start.main")啓動應用BActivity了。git

//App A
class AppAActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_app_a)
        btnStartAppB.setOnClickListener {
            startActivity(Intent("com.a.appb.start.main"))
        }
    }
}
複製代碼
//App B
class AppBActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_app_b)
    }
}

//AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   ...
        <activity android:name=".AppBActivity">
            ...
            <intent-filter>
                <action android:name="com.a.appb.start.main"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
   ...
</manifest>
複製代碼

調用過程

Activity.startActivity(Intent)
    
Activity.startActivity(Intent,Options)
    
Activity.startActivityForResult(Intent,RequestCode)
    
Activity.startActivityForResult(Intent,RequestCode,Options)

Instrumentation.execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options)

ActivityManagerNative.getDefault().startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);

ActivityManagerService.startActivity(IBinder whoThread, String callingPackage,
                Intent intent, String resolvedType, Bundle bOptions)

複製代碼

2.AMS.startActivity

ActivityManagerService.startActivity(whoThread,callingPackage,...)

ActivityManagerService.startActivityAsUser(IApplicationThread,callingPackage,...)

ActivityStarter.startActivityMayWait(IApplicationThread,callingUid,callingPackage,...) 

ActivityStarter.startActivityLocked(IApplicationThread,intent,ephemeralIntent,...)

ActivityStarter.startActivityUnchecked(ActivityRecord,sourceRecord,...)

ActivityStackSupervisor.resumeFocusedStackTopActivityLocked()

ActivityStack.resumeTopActivityUncheckedLocked(ActivityRecord prev,...) 

ActivityStack.resumeTopActivityInnerLocked(ActivityRecord prev,...)

ActivityStackSupervisor.startSpecificActivityLocked(ActivityRecord r,boolean andResume,...)

ActivityManagerService.startProcessLocked( processName,ApplicationInfo, ...) 
複製代碼

3.AMS.startProcess

ActivityManagerService.startProcessLocked( processName,ApplicationInfo, ...) 
Process.start(final String processClass, final String niceName,…) 
Process.startViaZygote(String processClass,String niceName,…)
Process.zygoteSendArgsAndGetResult( ZygoteState,  args)
ZygoteInit.runSelectLoop(String abiList)//Zygote被建立後啓動循環等待建立進程的請求
ZygoteConnection.runOnce()
Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, …)
Zygote.nativeForkAndSpecialize(
                  uid, gid, gids, debugFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
                  instructionSet, appDataDir)
com_android_internal_os_Zygote.com_android_internal_os_Zygote_nativeForkAndSpecialize(…)
com_android_internal_os_Zygote.ForkAndSpecializeCommon(…)
com_android_internal_os_Zygote.fork(…)
複製代碼

4.Zygote.fork

5.ActivityThread.main

ActivityManagerService.startProcessLocked( processName,ApplicationInfo, ...) 
Process.start(final String processClass, final String niceName,…) 
Process.startViaZygote(String processClass,String niceName,…)
Process.zygoteSendArgsAndGetResult( ZygoteState,  args)
ZygoteInit.runSelectLoop(String abiList)//Zygote被建立後啓動循環等待建立進程的請求
ZygoteConnection.runOnce()
Zygote.handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
RuntimeInit.zygoteInit(targetSdkVersion, remainingArgs,…);
RuntimeInit.applicationInit(targetSdkVersion,  argv, …)
RuntimeInit.invokeStaticMain(args.startClass, args.startArgs, …)
android.app.ActivityThread.main()
ActivityThread.attach(system:false)
ActivityManagerService.attachApplication(ApplicationThread)
ActivityManagerService.attachApplicationLocked(thread,callingPid)
複製代碼

6.AMS.attachApplication

ActivityManagerService.attachApplicationLocked(thread,callingPid)
	ApplicationThread.bindApplication(processName,ApplicationInfo,…)
		ActivityThead.handleBindApplication(AppBindData)
    		LoadedApk.makeApplication(forceDefaultAppClass,instrumentation)
    ActivityStackSupervisor.attachApplocationLocked(app)
    	ActivityStackSupervisor.realStartActivityLocked(ActivityRecord,ProcessRecord,...)
    	ApplicationThread.scheduleLauchActivity(intent,token,...)
複製代碼

7.ApplicationThread.scheduleLauchActivity

ApplicationThread.scheduleLauchActivity(intent,token,...)
H.sendMessage(H.LAUNCH_ACTIVITY, r)
ActivityThread.handleLaunchActivity(ActivityClientRecord,...)
複製代碼

什麼時候加載Application

public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
        .....
        Application app = null;
        String appClass = mApplicationInfo.className;
        java.lang.ClassLoader cl = getClassLoader(); 
        initializeJavaContextClassLoader();
               
        ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
        app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
        appContext.setOuterContext(app);
        mActivityThread.mAllApplications.add(app);
        mApplication = app;
        instrumentation.callApplicationOnCreate(app);
        ....

        return app;
    }
複製代碼
相關文章
相關標籤/搜索