Android之Handler和Loooper源码分析

1、handler在主线程和子线程互相通信(子线程和子线程的通信)简单使用

      我们使用handler,可以实现主线程和子线程之间的相互通信,然后子线程和子线程之间的通信,如果不清楚,基本用法请先参考我的这篇博客

Android之用Handler实现主线程和子线程互相通信以及子线程和子线程之间的通信  http://blog.csdn.net/u011068702/article/details/75577005

 
2、handler在主线程为什么不需要调用Looper.prepare()

我们看下Looper.java这个类,它在安卓android.os包下,我们看这个类的一开始的注释

 

      * <p>This is a typical example of the implementation of a Looper thread,
      * using the separation of {@link #prepare} and {@link #loop} to create an
      * initial Handler to communicate with the Looper.
      *
      * <pre>
      *  class LooperThread extends Thread {
      *      public Handler mHandler;
      *
      *      public void run() {
      *          Looper.prepare();
      *
      *          mHandler = new Handler() {
      *              public void handleMessage(Message msg) {
      *                  // process incoming messages here
      *              }
      *          };
      *
      *          Looper.loop();
      *      }
      *  }</pre>


很明显,在一个线程里面需要使用Handler之前需要Looper.prepare(),但是我们平时在主线程更新UI的时候,为什么没有看到这行代码呢?

 

我们看下ActivityThread.java这个类,它在安卓包名android.app目录下,我们知道ActivityThread.java这个类是安卓程序的入口,我们看下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());
     
            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("<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"));
            }

更多请见:http://www.mark-to-win.com/tutorial/52025.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值