Handle 源码解析(一)

20 篇文章 0 订阅

首先呢,都知道Handler里面有三个部分,handler、looper,messageQueue。

	那么我们先看一下关于Handler里面的源码Handler的构造方法里面有什么
  @Deprecated
    public Handler() {
        this(null, false);
    }

 @Deprecated
    public Handler(@Nullable Callback callback) {
        this(callback, false);
    }

   @UnsupportedAppUsage
    public Handler(boolean async) {
        this(null, async);
    }

通过以上的三个构造方法,可以发现他们走的都是一个构造方法,那再看一下,那个构造方法里面有什么呢

 public Handler(@Nullable Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

可以看到下面有一个判断这个mLoop == null 如果为空就会抛出一样。但是我们在主线程中使用Handler时也没有调用Loop,prepare()
没有创建Loop对象,为什么他不会崩溃呢,这个留在最后去解决,先看一下面的

 public Handler(@NonNull Looper looper) {
        this(looper, null, false);
    }
  public Handler(@NonNull Looper looper, @Nullable Callback callback) {
        this(looper, callback, false);
    }

以上这两块构造方法会走下面这个构造方法

  @UnsupportedAppUsage
    public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

接上面我们在主线程中使用Handler时也没有调用Loop,prepare(),但是为什么不会崩呢

 public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        // Install selective syscall interception
        AndroidOs.install();

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

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        // Call per-process mainline module initialization.
        initializeMainlineModules();

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

        Looper.prepareMainLooper();      //请看这里在ActivityThread源码中呢。他会调用perpareMainLooper()去创建一个主线程的loop

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        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。所以我们调用的时候不会崩
上面有注释(可能有些不好找,哈哈,看中文)

这就是关于Handler中的构造方法

下一篇呢会说一些关于MessageQueue了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值