Android 判断当前线程是否是主线程的两种方法

来源:互联网 发布:截拳道软件下载 编辑:程序博客网 时间:2024/05/21 10:49

使用Looper判断,方法为: Looper.myLooper() != Looper.getMainLooper()

使用线程句柄判断,将主线程的Thread.currentThread()获取到主线程当前句柄,保存起来,在需要判断的时候调用Thread.currentThread()来与之比较,即可判断当前线程是否是主线程了。


Handler一定要在主线程实例化吗?new Handler()和new Handler(Looper.getMainLooper())的区别
如果你不带参数的实例化:Handler handler = new Handler();那么这个会默认用当前线程的looper
一般而言,如果你的Handler是要来刷新操作UI的,那么就需要在主线程下跑。
情况:
1.要刷新UI,handler要用到主线程的looper。那么在主线程 Handler handler = new Handler();,如果在其他线程,也要满足这个功能的话,要Handler handler = new Handler(Looper.getMainLooper());
2.不用刷新ui,只是处理消息。 当前线程如果是主线程的话,Handler handler = new Handler();不是主线程的话,Looper.prepare(); Handler handler = new Handler();Looper.loop();或者Handler handler = new Handler(Looper.getMainLooper());
若是实例化的时候用Looper.getMainLooper()就表示放到主UI线程去处理。
如果不是的话,因为只有UI线程默认Loop.prepare();Loop.loop();过,其他线程需要手动调用这两个,否则会报错。

参考:http://blog.csdn.net/thanklife/article/details/17006865

0 0
原创粉丝点击