Android判断当前线程是否是主线程的方法
开发过程中有时候会在Thread类中执行某些操作,有些操作会由于Android版本的不同,尤其是低版本而Crash,因此必要的时候会查看某些容易引起crash的操作是否是在主线程,这里举2种方法:
方法一:使用Looper类判断
Looper.myLooper() == Looper.getMainLooper()
* Looper.myLooper()
Return the Looper object associated with the current thread. Returns
null if the calling thread is not associated with a Looper.
返回与当前线程关联的Looper对象。 如果调用线程没有与Looper关联,返回null。
* Looper.getMainLooper()
Returns the application's main looper, which lives in the main thread of the application.
返回应用application 中主线程的 looper。
方法二:通过查看Thread类的当前线程
Thread.currentThread() == Looper.getMainLooper().getThread()
* Thread.currentThread()
Returns the Thread of the caller, that is, the current Thread.
返回当前线程。
* Looper.getMainLooper().getThread()
返回应用application 中主线程的 looper相关的Thread 。