Android应用开发Android 进程创建流程介绍(Context的创建)
白羽 2019-03-15 来源 :网络 阅读 855 评论 0

摘要:本文将带你了解Android应用开发Android 进程创建流程介绍(Context的创建),希望本文对大家学Android有所帮助。

    本文将带你了解Android应用开发Android 进程创建流程介绍(Context的创建),希望本文对大家学Android有所帮助。



Android应用开发Android 进程创建流程介绍(Context的创建)


Android   APP进程的创建由ActivityThread这个类完成,下面本文分析下ActivityThread的初始化流程。
   
    流程介绍
    通过下面的流程图简单看下这个ActivityThread初始化的过程。
    \
   
    关键点:
      ActivityThread和AMS均为Binder对象,但是IActivityThread上有oneway关键字,所以系统调用IActivityThread为异步,但是IActivityThread调用AMS为同步。
    1. AMS的AIDL文件声明
    \
   
    2.IActivityManager的AIDL文件声明
    \
   
    ActivityThread
      如果需要启动一个APP进程,那么首先会调用到这个ActivityThread类main()方法,这个main()方法应该是有系统进行调用的,我们暂时不进行分析,先看下main方法。
   
  
    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,   ActivityThreadMain);
     
        // 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());
     
        // 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();
        // 关键部分,接下来要向AMS注册
        ActivityThread thread = new   ActivityThread();
        // 创建Application对象
        thread.attach(false);
     
        if (sMainThreadHandler == null)   {
            sMainThreadHandler =   thread.getHandler();
        }
     
        if (false) {
              Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG,   ActivityThread));
        }
     
        // End of event   ActivityThreadMain.
          Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        // Looper运行起来
        Looper.loop();
     
        throw new RuntimeException(Main   thread loop unexpectedly exited);
    }

    然后看下关键的attach()
   
  
    private void attach(boolean system) {
        sCurrentActivityThread =   this;
        mSystemThread = system;
        //   如果我们不是系统进程的话,只需要关心这一个if条件就行了。
        if (!system) {
              ViewRootImpl.addFirstDrawHandler(new Runnable() {
                @Override
                public void run() {
                      ensureJitEnabled();
                }
            });
              android.ddm.DdmHandleAppName.setAppName(,
                                                      UserHandle.myUserId());
              RuntimeInit.setApplicationObject(mAppThread.asBinder());
            //   请求AMS进行绑定,这个是一个异步的IPC操作。
            final IActivityManager mgr =   ActivityManager.getService();
            try {
                  mgr.attachApplication(mAppThread);
            } catch (RemoteException ex)   {
                throw   ex.rethrowFromSystemServer();
            }
            // Watch for getting close to   heap limit.
              BinderInternal.addGcWatcher(new Runnable() {
                @Override public void   run() {
                    if   (!mSomeActivitiesChanged) {
                        return;
                    }
                    Runtime runtime =   Runtime.getRuntime();
                    long dalvikMax =   runtime.maxMemory();
                    long dalvikUsed =   runtime.totalMemory() - runtime.freeMemory();
                    if (dalvikUsed >   ((3*dalvikMax)/4)) {
                        if   (DEBUG_MEMORY_TRIM) Slog.d(TAG, Dalvik max= + (dalvikMax/1024)
                                +  total= + (runtime.totalMemory()/1024)
                                +  used= + (dalvikUsed/1024));
                          mSomeActivitiesChanged = false;
                        try {
                              mgr.releaseSomeActivities(mAppThread);
                        } catch   (RemoteException e) {
                            throw   e.rethrowFromSystemServer();
                        }
                    }
                }
            });
        } 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 =   ContextImpl.createAppContext(
                        this,   getSystemContext().mPackageInfo);
                // 创建Application
                mInitialApplication =   context.mPackageInfo.makeApplication(true, null);
                mInitialApplication.onCreate();
            } catch (Exception e) {
                throw new   RuntimeException(
                        Unable to   instantiate Application(): + e.toString(), e);
            }
        }
     
        // add dropbox logging to   libcore
        DropBox.setReporter(new   DropBoxReporter());
     
          ViewRootImpl.ConfigChangedCallback configChangedCallback
                = (Configuration   globalConfig) -> {
            synchronized   (mResourcesManager) {
                // We need to apply this   change to the resources immediately, because upon returning
                // the view hierarchy   will be informed about it.
                if   (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
                        null /* compat   */)) {
                      updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
                            mResourc 


 

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之Android频道!

本文由 @白羽 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程