Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically determine whether the code is executing from the UI thread or not

Tags:

android

In my Android app, I am extracting the code to update UI elements into a separate utility package for reuse. I would like my code to be proactive and update the UI differently if the current execution context is from a UI thread versus a non-UI thread.

Is it possible to programmatically determine whether the current execution is happening on the UI thread or not?

A trivial example of what I am looking to achieve is this - my app updates a lot of TextViews all 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 obviously won't work if called from a non-UI thread. In that case I would like to force the client code to pass in a Handler as well, and post the UI operation to the handler.

like image 718
curioustechizen Avatar asked Nov 15 '11 14:11

curioustechizen


2 Answers

Why don't you use the runOnUiThread method in Activity

It takes a runnable and either runs it straight away (if called from the UI thread), or will post it to the event queue of the UI thread.

That way you don't have to worry about if your method has been called from the UI thread or not.

like image 54
kingraam Avatar answered Sep 26 '22 03:09

kingraam


When you're not sure the code is executed on the UI thread, you should do:

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

This way, whether you're on the UI thread or not, it will be executed there.

like image 42
Guillaume Avatar answered Sep 23 '22 03:09

Guillaume