美文网首页
Android判断当前线程是否是主线程的方法

Android判断当前线程是否是主线程的方法

作者: 银弹星空 | 来源:发表于2019-07-20 12:26 被阅读0次

Android开发中, 有时需要判断当前线程到底是主线程, 还是子线程, 例如: 我们在自定义View时, 想要让View重绘, 需要先判断当前线程到底是不是主线程, 然后根据判断结果来决定到底是调用 invalidate() 还是 postInvalidate() 方法. 如果当前是主线程, 就调用 invalidate() 方法; 而如果当前是子线程, 就调用 postInvalidate() 方法, 注意: 子线程中不能调用 invalidate() 方法, 否则就会报异常, 提示我们不能在子线程中更新UI。有的方法执行没有反应,有可能就是线程问题。

方法一:使用Looper类判断

Looper.myLooper() == Looper.getMainLooper()

方法二:通过查看Thread类的当前线程

Thread.currentThread() == Looper.getMainLooper().getThread()

相关文章

网友评论

      本文标题:Android判断当前线程是否是主线程的方法

      本文链接:https://www.haomeiwen.com/subject/dxnylctx.html