Activity工作过程(2)-《Andoid开发艺术探索》《深入解析Android5.0系统》结合分析

先看这张图吧:

Activity工作过程(2)-《Andoid开发艺术探索》《深入解析Android5.0系统》结合分析_第1张图片
ScreenClip.png

在这些类的调用过程中,尤其是在ActivityStack和ActivityStackStack这两个类中都在频繁的操控Activity的生命周期调度,
这个是Activity onCreate()的调度方法:

app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                    r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,
                    results, newIntents, !andResume, mService.isNextTransitionForward(),
                    profilerInfo);

这个是 Activity onResume( ) 的调度方法:

next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
                    mService.isNextTransitionForward(), resumeAnimOptions);

这里的app.thread到底是何方神圣,为什么不直接操作Activity而是要通过这样一个app.Thread(app.Thread并不是Thread)?
先认识下这个Thread
/**

  • System private API for communicating with the application. This is given to
  • the activity manager by an application when it starts up, for the activity
  • manager to tell the application about things it needs to do.
  • {@hide}
    */
    public interface IApplicationThread extends IInterface
    其内部包含了大量启动,停止Activity的接口还包含了启动和停止服务的接口从命名可以看出,IApplicationThread 这个Binder接口的实现者完成了大量的Activity以及Service启动/停止相关的功能。
    那我们就来看看IApplicationThread 的实现类:
    public abstract class ApplicationThreadNative extends Binder implements IApplicationThread
    虽然这个是抽象类,但是其中也做了相当多的操作如:
class ApplicationThreadProxy implements IApplicationThread {
    ···
public final void scheduleResumeActivity(IBinder token, int procState, boolean isForward,
            Bundle resumeArgs)
            throws RemoteException {
        Parcel data = Parcel.obtain();
        data.writeInterfaceToken(IApplicationThread.descriptor);
        data.writeStrongBinder(token);
        data.writeInt(procState);
        data.writeInt(isForward ? 1 : 0);
        data.writeBundle(resumeArgs);
        mRemote.transact(SCHEDULE_RESUME_ACTIVITY_TRANSACTION, data, null,
                IBinder.FLAG_ONEWAY);
        data.recycle();
    }
    ···
 }

没错,这就是系统为AIDL文件自动生成的代理类。

ActivityThread有个内部类ApplicationThread ,
private class ApplicationThread extends ApplicationThreadNative

最终回到了ApplicationThread 的 scheduleLaunchActivity()

// we use token to identify this activity without having to send the
// activity itself back to the activity manager. (matters more with ipc)
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
                IVoiceInteractor voiceInteractor, int procState, Bundle state,
                PersistableBundle persistentState, List pendingResults,
                List pendingNewIntents, boolean notResumed, boolean isForward,
                ProfilerInfo profilerInfo) {

            updateProcessState(procState, false);

            ActivityClientRecord r = new ActivityClientRecord();
                ···
            updatePendingConfiguration(curConfig);

            sendMessage(H.LAUNCH_ACTIVITY, r);
        }

没啥难度,重点在最后一句,发送一个启动Activity的消息给ActivityThread内部的Handler;
哪里有handler?额,它有个大方且帅气的名字:
private class H extends Handler
呵呵 , 我方了
看看我们的H干了点啥:

 case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } 
   break;

这里只是等待处理完成后关闭trace,算是完成了一次进程间通信,有读取有回写,相当完美。
回到重点:

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ···
        //开启activity的create之旅
        Activity a = performLaunchActivity(r, customIntent);
        //启动完毕接下来进入onResume()
        if (a != null) {
        ···
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);

        }
    }

在这之前其实有个小小的疑问,这时候Handler为什么可以调用?(虽然我们是从startActivity开始,但是如果应用刚刚开始,这个ActivityThread一定会在App启动的时候悄悄搞点事情)而且拉风的H竟然还掌控着Activity的生命周期,这个神奇的UIThread到底是什么时候,被谁创建出来的呢?
答案在ApplicationInit()里:
ApplicationInit()除了设置虚拟机的两个参数外,最重要的是调用了invokeStaticMain(args.startClass,args.startArgs),调用的参数args.startClass是通过socket传入的,通常是“android.app.ActivityThread”这样将会调用ActivityThread的main()方法。但是invokeStaticMain()并不是直接调用main()方法,而是抛出了一个Exception:

throw new ZygoteInit.MethodAndArgsCaller(m,argv);

在 ZygoteInit的mian()方法中会catch这个Exception:

catch (MethodAndArgsCaller caller){
    caller.run();
}

这里为什么要先抛出一个Exception是因为从ZygoteInit调用开始到最终进入invokeStaticMain()系统的栈里面已经累积了不少调用帧,调用ActivityThread的mian()函数不会返回,为了能清除前面的调用栈帧,给新运行的应用一个干净的环境,才使用了throw Exception的方式。

 public static void main(String[] args) {
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        Security.addProvider(new AndroidKeyStoreProvider());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
//设置进程名称
        Process.setArgV0("");
//初始化Looper
        Looper.prepareMainLooper();
//创建ActivityThread 
        ActivityThread thread = new ActivityThread();
        //通过False主动调用attach
        thread.attach(false);

        if (sMainThreadHandler == null) {//保存主线程的Handler
            sMainThreadHandler = thread.getHandler();
        }

        AsyncTask.init();//初始化AsyncTask类

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

看看ActivityThread 的 attach()都绑定了什么 :

private void attach(boolean system) {
       ···
        if (!system) {
           ···
            android.ddm.DdmHandleAppName.setAppName("",
                                                    UserHandle.myUserId());
            //把ApplicationThread对象放到RuntimeInit中
            RuntimeInit.setApplicationObject(mAppThread.asBinder());
            final IActivityManager mgr = ActivityManagerNative.getDefault();
            try {
            //把ApplicationThread传入AMS并调用AMS的attachApplication()
                mgr.attachApplication(mAppThread);
            } catch (RemoteException ex) {
                // Ignore
            }
           ···
        } else {
            ···
        }

     ···
    }

竟然推着ActivityManagerService也跟着动了起来:

attachApplication( ) -> attachApplicationLocked( ) ->ApplicationThread.bindApplication( )
这里bindApplication()会发送消息BIND_APPLICATION

private void handleBindApplication(AppBindData data)

这里主要作用就是创建应用框架中的各种对象:
InstrumentationInfo
Instrumentation
ApplicationInfo
Application
LoadedApk
ContextImpl
···

->mStackSupervisor.attachApplicationLocked()->mStackSupervisor.realSrartActivityLocked( )
这个方法里做了判断,如果进程没有启动则启动进程,如果进程启动了则调用Activity的onResume( )
最后用图说话(后来补上的):

Activity工作过程(2)-《Andoid开发艺术探索》《深入解析Android5.0系统》结合分析_第2张图片
QQ图片20170329233031.png

你可能感兴趣的:(Activity工作过程(2)-《Andoid开发艺术探索》《深入解析Android5.0系统》结合分析)