如何知道这个线程是UI线程 [英] How to know if this thread is a UI Thread

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

问题描述

有没有办法在Android上就知道了,如果线程运行我的code,是在UI线程与否?在摆有 SwingUtilities.isEventDispatchThread()来告诉我,如果我在UI线程,还是不行。有没有在Android SDK中的任何功能,可以让我知道这一点?

解决方案
  1. 答案从这里借来的:<一href="http://stackoverflow.com/questions/11411022/how-to-check-if-current-thread-is-not-main-thread">How检查当前线程不是主线程

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

  2. 所有的Andr​​oid应用只有一个UI线程,所以你可以在某个地方像的onCreate活动回调()查看和存储其ID,后来只是线程的ID比较存储之一。

    mMainThreadId = Thread.currentThread()的getId();

  3. 无论如何,你可以省略检查,如果你想要做的事在UI线程上,并通过使用有任何引用到活动

      mActivity.runOnUiThread(新的Runnable(){
        @覆盖
        公共无效的run(){
        ...
        }
    });
     

这是保证当前的线程上运行,如果它的用户界面,或排队UI线程。

Is there any way on Android to know, if the thread running my code, is the UI Thread or not ? In swing there was SwingUtilities.isEventDispatchThread() to tell me if i am on the UI Thread, or not. Is there any function in the Android SDK that lets me know this ?

解决方案

  1. Answer borrowed from here: How to check if current thread is not main thread

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

  2. Any Android app has only one UI thread, so you could somewhere in the Activity callback like onCreate() check and store its ID and later just compare that thread's ID to the stored one.

    mMainThreadId = Thread.currentThread().getId();

  3. Anyway, you can omit checking if you want to do something on the UI thread and have any reference to Activity by using

    mActivity.runOnUiThread( new Runnable() {
        @Override 
        public void run() {
        ...
        }
    });
    

which is guaranteed to run on current thread, if it's UI, or queued in UI thread.

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

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