如何检测UI线程在Android? [英] How to detect UI thread on Android?

查看:119
本文介绍了如何检测UI线程在Android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种可靠的方法来检测是否 Thread.currentThread()是在应用程序的Andr​​oid系统UI线程?
我想提出一些主张在我的模型code断言只有一个线程(例如 UI线程)访问我的状态,以确保没有那种同步是必要的。

Is there a robust way to detect if Thread.currentThread() is the Android system UI thread in an application?
I would like to put some asserts in my model code that asserts that only one thread (eg the ui thread) accesses my state, to assure that no kind of synchronization is necessary.

推荐答案

通常的做法,以确定UI线程的身份通过的尺蠖#getMainLooper

Common practice to determine the UI Thread's identity is via Looper#getMainLooper:

if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
  // On UI thread.
} else {
  // Not on UI thread.
}

这篇关于如何检测UI线程在Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆