我需要检查运行某段代码的线程是否是主(UI)线程。我怎样才能做到这一点?
答案 0 :(得分:628)
Looper.myLooper() == Looper.getMainLooper()
如果返回true,那么你就在UI线程上了!
答案 1 :(得分:105)
您可以使用以下代码来了解当前线程是否是UI /主线程
if(Looper.myLooper() == Looper.getMainLooper()) {
// Current Thread is Main Thread.
}
或者您也可以使用此
if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
// Current Thread is Main Thread.
}
答案 2 :(得分:44)
最好的方法是最清晰,最强大的方式:*
Thread.currentThread().equals( Looper.getMainLooper().getThread() )
或者,如果运行时平台是API级别23(Marshmallow 6.0)或更高级别:
Looper.getMainLooper().isCurrentThread()
请参阅Looper API。请注意,调用Looper.getMainLooper()
涉及同步(请参阅source)。您可能希望通过存储返回值并重用它来避免开销。
* 信用greg7gkb和2cupsOfTech
答案 3 :(得分:19)
总结解决方案,我认为这是最好的解决方案:
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
}
});
答案 4 :(得分:3)
您可以检查
if(Looper.myLooper() == Looper.getMainLooper()) {
// You are on mainThread
}else{
// you are on non-ui thread
}
答案 5 :(得分:1)
你可以在android ddms logcat中验证它,其中进程id将是相同的但是线程id将是不同的。
答案 6 :(得分:1)
允许我以此开头: 我承认该帖子带有“ Android”标签,但是,我的搜索与“ Android”无关,这是我的最高搜索结果。为此,对于非Android SO Java用户登陆此处,请不要忘记:
import 'package:flutter/material.dart';
class ApiWidget extends StatefulWidget {
@override
_ApiWidgetState createState() => _ApiWidgetState();
}
class _ApiWidgetState extends State<ApiWidget> {
Repository _repository = Repository();
Future<AccessToken> accessTokenFuture;
bool isButtonPressed = false;
@override
Widget build(BuildContext context) {
return Column(children: <Widget>[
FloatingActionButton(onPressed: () {
setState(() {
try {
isButtonPressed = true;
accessTokenFuture = fetchAccessToken();
} catch (_) {
print('Fetch error');
}
});
}, child: Icon(Icons.add),),
if(isButtonPressed)
FutureBuilder<AccessToken>(
future: bloc.fetchAccessToken(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Text('Error');
}
Column(
children: <Widget>[Text(snapshot.data)],
);
},
),
],);
}
}
设置此选项后,您可以在代码的其他位置使用以下命令轻松检查是否要在主线程上执行:
public static void main(String[] args{
Thread.currentThread().setName("SomeNameIChoose");
/*...the rest of main...*/
}
在记住这一点之前我曾搜索过一些尴尬,但希望它将对其他人有所帮助!
答案 7 :(得分:0)
Xamarin.Android
端口:( C#
)
public bool IsMainThread => Build.VERSION.SdkInt >= BuildVersionCodes.M
? Looper.MainLooper.IsCurrentThread
: Looper.MyLooper() == Looper.MainLooper;
用法:
if (IsMainThread) {
// you are on UI/Main thread
}
答案 8 :(得分:0)
一条简单的 Toast 消息也可以作为快速检查。
答案 9 :(得分:-6)
您可以尝试Thread.currentThread()。isDaemon()