Programmatically determine whether code is being executed from a user interface thread or not.

In my Android application, I extract the code to update the user interface elements into a separate utility package for reuse. I would like my code to be active and update the user interface differently if the current execution context is from a user interface thread versus a non-UI thread.

Is it possible to programmatically determine whether the current execution is in progress on a user interface thread or not?

A trivial example of what I'm looking for is my application, which updates a lot TextViewall the time. So, I would like to have a static utility like this:

public static void setTextOnTextView(TextView tv, CharSequence text){
    tv.setText(text);
}

This will obviously not work if called from a thread other than the UI. In this case, I would like to force the client code to pass in Handler, and also send the UI operation to the handler.

+5
source share
3 answers

Why don't you use the runOnUiThread method in Activity

It runs runnable and either starts it right away (if called from the user interface thread) or sends it to the event queue of the user interface thread.

This way you don't have to worry about whether your method is called from the user interface thread or not.

+4
source

When you are not sure if the code is executing in the user interface thread, you should do:

activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // your code here
    }
});

, , , .

+1

You can use the View post method .

Your code will look like this:

tv.post(new Runnable() {

  public void run() {
     tv.setText(text);
  }

});
0
source

All Articles