Car*_*nal 677
Looper.myLooper() == Looper.getMainLooper()
Run Code Online (Sandbox Code Playgroud)
如果这返回true,那么你就是UI线程!
AAn*_*kit 116
您可以使用下面的代码来了解当前线程是否是UI /主线程
if(Looper.myLooper() == Looper.getMainLooper()) {
// Current Thread is Main Thread.
}
Run Code Online (Sandbox Code Playgroud)
或者你也可以使用它
if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
// Current Thread is Main Thread.
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*lan 55
最好的方法是最清晰,最强大的方式:*
Thread.currentThread().equals( Looper.getMainLooper().getThread() )
Run Code Online (Sandbox Code Playgroud)
或者,如果运行时平台是API级别23(Marshmallow 6.0)或更高级别:
Looper.getMainLooper().isCurrentThread()
Run Code Online (Sandbox Code Playgroud)
请参阅Looper API.请注意,调用Looper.getMainLooper()涉及同步(请参阅源代码).您可能希望通过存储返回值并重用它来避免开销.
and*_*per 23
总结解决方案,我认为这是最好的解决方案:
boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M
? Looper.getMainLooper().isCurrentThread()
: Thread.currentThread() == Looper.getMainLooper().getThread();
Run Code Online (Sandbox Code Playgroud)
而且,如果您希望在UI线程上运行某些东西,可以使用:
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//this runs on the UI thread
}
});
Run Code Online (Sandbox Code Playgroud)
你可以检查一下
if(Looper.myLooper() == Looper.getMainLooper()) {
// You are on mainThread
}else{
// you are on non-ui thread
}
Run Code Online (Sandbox Code Playgroud)
首先检查它是否是主线程
在科特林中
fun isRunningOnMainThread(): Boolean {
return Thread.currentThread() == Looper.getMainLooper().thread
}
Run Code Online (Sandbox Code Playgroud)
爪哇语
static boolean isRunningOnMainThread() {
return Thread.currentThread().equals(Looper.getMainLooper().getThread());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
111054 次 |
| 最近记录: |