Friday, 12 September 2014

Android - Are we in the main thread

The main thread of Android is taking care of the interaction with the user and it shouldn't be used for time consuming tasks. For those tasks, they should be run in a separate thread.

But for some specific tasks which are related with changes on the UI, they must be executed on the main thread. Otherwise the app could crash due to an exception.

To avoid this problem, it could be good to check if the running thread is the main thread or not. To do so, execute the follow sentence.  

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

Or you can use:

    if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
        return true;
    }

Source:

No comments:

Post a Comment