Handler运行机制源码分析

Handler运行机制源码分析

问题提出

  • Handler和Android程序运行关系
  • Handler如何Android消息队列
  • Hanlder存在的意义

核心内容

  • 作为Android开发人员都知道,Android App是单进程运行的,而在这个进程里面有一个主线程,这个主线程在代码中称作:android.app.ActivityThread,该类负责管理和执行主线程里面的四大组件相关联的操作。主线程里面的main函数就是整个app的启动入口。我们来瞄一眼代码:

  • public static void main(String[] args) {
    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
    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());
    
    AndroidKeyStoreProvider.install();
    
    // Make sure TrustedCertificateStore looks in the right place for CA certificates
    final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
    TrustedCertificateStore.setDefaultUserDirectory(configDir);
    
    Process.setArgV0("<pre-initialized>");
    
    Looper.prepareMainLooper();
    
    ActivityThread thread = new ActivityThread();
    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.loop();
    
    throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    
  • 上面的主要代码是从Looper.prepareMainLooper();开始的,在这之前的代码大部分都是app的初始化和配置工作。关于prepareMainLooper()具体工作带回描述,先捋顺流程提问题然后在逐个解决,在Looper初始化完成之后,初始化了当前的主线程(主要工作:进行主线程操作,比如平时的UI设置),然后初始化了主线程的Handler,虽然是通过thread.getHandler()调用的,但是他们之间是如何进行通信的呢?thread.getHandler()是继承了Hanlder,用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值