我需要检查运行某段代码的线程是否是主(UI)线程。我怎样才能做到这一点呢?


当前回答

除了之前所有的答案

inline fun <T> ensureNotOnMainThread(block: () -> T): T {
    check(Thread.currentThread() != Looper.getMainLooper().thread) { "This function cannot be called on main thread" }
    return block()
}

允许用它包装任何方法,示例如下:

fun isInDataBase(id: String) = ensureNotOnMainThread { db.contains(id) }

其他回答

你可以在android DDMS logcat中验证它,其中进程id将是相同的,但线程id将不同。

你可以使用下面的代码来知道当前线程是否是UI/主线程

if(Looper.myLooper() == Looper.getMainLooper()) {
   // Current Thread is Main Thread.
}

或者你也可以用这个

if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
   // Current Thread is Main Thread.
}

这里有一个类似的问题

你可以检查一下

if(Looper.myLooper() == Looper.getMainLooper()) {
   // You are on mainThread 
}else{
// you are on non-ui thread
}

总结解决方案,我认为这是最好的一个:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M 
    ? Looper.getMainLooper().isCurrentThread()
    : Thread.currentThread() == Looper.getMainLooper().getThread();

并且,如果你想在UI线程上运行一些东西,你可以使用这个:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
       //this runs on the UI thread
    }
});

简单的Toast消息也可以作为快速检查。