Android8.1源码讲解之ActivityThread启动Activity

本文深入探讨Android8.1的ActivityThread启动Activity的细节,从ActivityThread的main方法开始,讲解AMS的attachApplication过程,包括StackSupervisor的attachApplicationLocked和realStartActivityLocked步骤,再到ApplicationThread如何通过scheduleLaunchActivity、Handler消息处理,直至handleLaunchActivity和performLaunchActivity,完成Activity的启动。文章最后对整个流程进行了总结,并预告了后续可能涉及的深入话题。
摘要由CSDN通过智能技术生成

在上一篇文章有说ActivityThread启动的过程,最后讲解到ActivityThread的main函数启动。这篇文章接上篇文章讲解main方法中怎么启动Activity的,方便日后讲解有关Activity中的事件处理机制。

一、ActivityThread中main方法

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());

    Process.setArgV0("<pre-initialized>");

    //准备主线程中的Loop启动
    Looper.prepareMainLooper();
    //创建ActivityThread实例
    ActivityThread thread = new ActivityThread();
    //ActivityThread内容绑定
    thread.attach(false);

    if (sMainThreadHandler == null) {
 //获取主线程中的Handler
        sMainThreadHandler = thread.getHandler();
    }

    AsyncTask.init();

    if (false) {
        Looper.myLooper().setMessageLogging(new
                LogPrinter(Log.DEBUG, "ActivityThread"));
    }
    //启动主线中的Handler消息机制的loop
    Looper.loop();

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

这里完成了ActivityThread的实例的创建,然后进行绑定操作。在这里还完成了主线程也就是UI中的looper的启动,以便日后使用Handler消息机制。接下来要看一下ActivityThread的绑定Application的过程,接下来看一下ActivityThread中的attach方法。

//在这里是启动的ActivityThread不是系统,在main方法中已经看到传递过来的是false
private void attach(boolean system) {
    sThreadLocal.set(this);
    mSystemThread = system;
    if (!system) {
        ViewRootImpl.addFirstDrawHandler(new Runnable() {
            public void run() {
                ensureJitEnabled();
            }
        });
        android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
                UserHandle.myUserId());
        RuntimeInit.setApplicationObject(mAppThread.asBinder());
        //获取远程AMS的代理对象
        IActivityManager mgr = ActivityManagerNative.getDefault();
        //调用AMS中attachApplication方法,mAppThread在类加载的时候已经进行了初始化
        //在以后Activity的start、stop、resume以及显示都是mAppThread进行的
        try {
            mgr.attachApplication(mAppThread);
        } catch (RemoteException ex) {
            // Ignore
        }
    } else {
        // Don't set application object here -- if the system crashes,
        // we can't display an alert, we just want to die die die.
        android.ddm.DdmHandleAppName.setAppName("system_process",
                UserHandle.myUserId());
        try {
            mInstrumentation = new Instrumentation();
            ContextImpl context = new ContextImpl();
            context.init(getSystemContext().mPackageInfo, null, this);
            Application app = Instrumentation.newApplication(Application.class, context);
            mAllApplications.add(app);
            mInitialApplication = app;
            app.onCreate();
        } catch (Exception e) {
            throw new RuntimeException(
                    "Unable to instantiate Application():" + e.toString(), e);
        }
    }

    // add dropbox logging to libcore
    DropBox.setReporter(new DropBoxReporter());

    ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
        public void onConfigurationChanged(Configuration newConfig) {
            synchronized (mPackages) {
                // We need to apply this change to the resources
                // immediately, because upon returning the view
                // hierarchy will be informed about it.
                if (applyConfigurationToResourcesLocked(newConfig, null)) {
                    // This actually changed the resources!  Tell
                    // everyone about it.
                    if (mPendingConfiguration == null ||
                            mPendingConfiguration.isOtherSeqNewer(newConfig)) {
                        mPendingConfiguration = newConfig;

                        queueOrSendMessage(H.CONFIGURATION_CHANGED, newConfig);
                    }
                }
            }
        }
        public void onLowMemory() {
        }
        public void onTrimMemory(int level) {
        }
    });
}
在这里获取到远程AMS的代理对象,然后调用AMS方法进行Application的绑定工作。在这里有说到mAppThread这个成员变量,是ApplicationThreadNative的实例,在以后的操作Activity的操作都是在ApplicationThreadNative中进行的,这里不在详说。接下来就又回到了AMS中。

二、AMS中attachApplication

1、AMS的attachApplication

@Override
public final void attachApplication(IApplicationThread thread) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final long origId = Binder.clearCallingIdentity();
        attachApplicationLocked(thread, callingPid);
        Binder.restoreCallingIdentity(origId);
    }
}

private final boolean attachApplicationLocked(IApplicationThread thread,
                                              int pid) {

    // Find the application record that is being attached...  either via
    // the pid if we are running in multiple processes, or just pull the
    // next app record if we are emulating process with anonymous threads.
    ProcessRecord app;
    long startTime = SystemClock.uptimeMillis();
    if (pid != MY_PID && pid >= 0) {
        synchronized (mPidsSelfLocked) {
            //由pid获取进程记录
            app = mPidsSelfLocked.get(pid);
        }
    } else {
        app = null;
    }

    if (app == null) {
 //如果不存在则做相应处理
        Slog.w(TAG, "No pending application record for pid " + pid
                + " (IApplicationThread " + thread + "); dropping process");
        EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
        if (pid > 0 && pid != MY_PID) {
            killProcessQuiet(pid);
            //TODO: killProcessGroup(app.info.uid, pid);
        } else {
            try {
                thread.scheduleExit();
            } catch (Exception e) {
                // Ignore exceptions.
            }
        }
        return false;
    }

    // If this application record is still attached to a previous
    // process, clean it up now.
    //如果当前进程记录已经和其他应用进程绑定了这里进行删除操作
    if (app.thread != null) {
        handleAppDiedLocked(app, true, true);
    }

    // Tell the process all about itself.

    if (DEBUG_ALL) Slog.v(
            TAG, "Binding process pid " + pid + " to record " + app);

    final String processName = app.processName;
    try {
        AppDeathRecipient adr = new AppDeathRecipient(
                app, pid, thread);
        thread.asBinder().linkToDeath(adr, 0);
        app.deathRecipient = adr;
    } catch (RemoteException e) {
        app.resetPackageList(mProcessStats);
        startProcessLocked(app, "link fail", processName);
        return false;
    }

    EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);

    </
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值