android开发分享如何检查当前线程是否不是主线程

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

    Looper.myLooper() == Looper.getMainLooper() 

    如果这返回true,那么你在UI线程上!

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

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

    或者你也可以使用这个

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

    这是类似的问题

    最好的方法是最清晰的方式:*

     Thread.currentThread() == Looper.getMainLooper().getThread() 

    或者,如果运行时平台是API级别23(棉花糖6.0)或更高:

     Looper.getMainLooper().isCurrentThread() 

    请参阅Looper API 。 请注意,调用Looper.getMainLooper()涉及同步(参见源代码 )。 您可能希望通过存储返回值并重新使用它来避免开销。

    * 信用greg7gkb

    总结解决scheme,我认为这是最好的:

      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 } }); 

    你可以在android ddms logcat中validation它的进程ID是相同的,但是线程ID将是不同的。

    你可以尝试Thread.currentThread()。isDaemon()

      以上就是android开发分享如何检查当前线程是否不是主线程相关内容,想了解更多android开发(异常处理)及android游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/addevelopment/518585.html

      (0)
      上一篇 2020年12月6日
      下一篇 2020年12月6日

      精彩推荐