Análisis del proceso de carga de Android (desde el inicio de la aplicación hasta la ejecución de onCreate)

La entrada principal del software de Android es también main, este método principal se define en ActivityThread:

public static void main(String[] args) {
    
    
    ...
    Looper.prepareMainLooper();

    ActivityThread thread = new ActivityThread();
    thread.attach(false);

    if (sMainThreadHandler == null) {
    
    
        sMainThreadHandler = thread.getHandler();
    }
	...
        
    Looper.loop();
	...
}

El Handlermecanismo se usa principalmente aquí . Dado que este artículo habla principalmente sobre el mecanismo de carga de Android, no es demasiado análisis Handler. mainHay principalmente uno de los métodos, que Loopersiempre está esperando el mensaje ( Message). mainLa mayoría de los métodos son Handleralgunas operaciones del hilo principal . Lo importante es:

thread.attach(false);

Ver attachmétodo

private void attach(boolean system) {
    
    
    ...
    final IActivityManager mgr = ActivityManager.getService(); //1
    try {
    
    
        mgr.attachApplication(mAppThread);  //2
    } catch (RemoteException ex) {
    
    
        throw ex.rethrowFromSystemServer();
    }
    ...
}

1 obtenido en IActivityManagerun objeto mgr, el objeto es un sistema a través de un Bindermecanismo creado una Activityclase de gestión, llamado por los servicios del sistema de gestión, y por binderinterfaces de llamada entre.

El ApplicationThreadobjeto en 2 mAppThreades ActivityThreaduna variable miembro y la clase también es ActivityThreaduna clase interna

private class ApplicationThread extends IApplicationThread.Stub {
    
    
    public final void scheduleResumeActivity(IBinder token, int processState,
    boolean isForward, Bundle resumeArgs) {
    
    
		...
        sendMessage(H.RESUME_ACTIVITY, token, isForward ? 1 : 0, 0, seq);
    }

    // we use token to identify this activity without having to send the
    // activity itself back to the activity manager. (matters more with ipc)
    @Override
    public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
    ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
    CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
    int procState, Bundle state, PersistableBundle persistentState,
    List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
    boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
    
    
		...
        sendMessage(H.LAUNCH_ACTIVITY, r);
    }
    ...
}

Ese mgrsistema operativo (una llamada de servicio del sistema), mientras que ApplicationThreadsolo ActivityThreadla clase interna, llama a mgrla attachApplicationrelación para que la aplicación de Android construya el sistema operativo, el sistema operativo después de recibir el evento correspondiente, mediante ApplicationThreadel método de envío a la aplicación Información del sistema . Por ejemplo, cuando el usuario abre la aplicación, el sistema llamará mgrindirectamente a scheduleLaunchActivityeste método para Handlerenviar información al hilo principal :

sendMessage(H.LAUNCH_ACTIVITY, r);

Vista Handlerdel handlerMessagemétodo

public void handleMessage(Message msg) {
    
    
    ...
    switch (msg.what) {
    
    
        case LAUNCH_ACTIVITY: {
    
    
            ...
            final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
            handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
        } break;
        ...
    }
}

ActivityClientRecordEl objeto guarda los parámetros pasados ​​por el sistema, verhandleLaunchActivity

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
    
    
    Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
    
    
    	...
        handleResumeActivity(r.token, false, r.isForward,
            !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
        ...
    }
    ...
}

Este método principalmente ejecuta Activityla carga (Lanzamiento) o Reanudar el trabajo, continúe viendo performLaunchActivity:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    
    
    ...
    try {
    
    
		...
        if (activity != null) {
    
    
            ...
            if (r.isPersistable()) {
    
    
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
    
    
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
        }
    }
    return activity;     
}	

Formas de ver mInstrumentationobjetoscallActivityOnCreate

public void callActivityOnCreate(Activity activity, Bundle icicle,
	PersistableBundle persistentState) {
    
    
	prePerformCreate(activity);
	activity.performCreate(icicle, persistentState);
	postPerformCreate(activity);
}

Desde el nombre por encima de tres métodos de vista, que está hecho principalmente Activityde Create, ha Createdelantera y trasera (pre y post) de trabajo, ver performCreateMétodos

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    
    
	...
    if (persistentState != null) {
    
    
        onCreate(icicle, persistentState);
    } else {
    
    
        onCreate(icicle);
    }
    ...
}

A lo cual amaneció, Handleral recibir la información correspondiente (luego Messageejecuta la operación), y finalmente llama Activityal onCreatemétodo, completando así Activityel Launchproceso.

Supongo que te gusta

Origin blog.csdn.net/weixin_48968045/article/details/114499320
Recomendado
Clasificación