Android 如何判断当前线程是否是主线程

来源:互联网 发布:软件项目管理总结报告 编辑:程序博客网 时间:2024/05/17 23:56

source:http://blog.csdn.net/clevergump/article/details/50995612


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

这里写图片描述

那么, 我们如何判断当前线程到底是主线程, 还是子线程呢? 答案是: 可以借助于 Looper. 代码如下:

public boolean isMainThread() {    return Looper.getMainLooper() == Looper.myLooper();}

或者

public boolean isMainThread() {    return Looper.getMainLooper().getThread() == Thread.currentThread();}

或者

public boolean isMainThread() {    return Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();}

以上几种写法都可以.


end