Chaoz
Chaoz

Reputation: 2261

How much of this code should be inside the UI Thread?

So I have an AsyncTask doing some work in the background. The work is actually a list of commands that are done in a for loop. All commands may run the following method (inside the for loop):

public void print() {
    // Create and add a TextView
    // Variable "c" is the Activity reference, I get it in the constructor by passing "this" from the Activity
    TextView tv = new TextView(c);
    // Set its text
    tv.setText(text);
    // Set the style
    tv.setTextColor(Color.WHITE);
    tv.setTextSize(fontSize);
    tv.setSingleLine(false);
    // Add it to the linear layout
    display.addView(tv);
    // Add a spacer
    View spacer = new View(c);
    // Set bg color
    spacer.setBackgroundColor(Color.argb(0x88, 0, 0, 0));
    // Set width and height
    spacer.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, separatorHeight));
    // Add it to the layout
    display.addView(spacer);
    // Screen should update
    displayChanged = true;
}

At the end of the for loop I have this line:

if (displayChanged) updateScreen();

And finally the updateScreen() method:

private void updateScreen() {
    // Surround the linear layout with a vertical scroll view
    ScrollView scrollView = new ScrollView(c);
    scrollView.setVerticalScrollBarEnabled(false);
    scrollView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
    scrollView.addView(display);
    // Set code background color
    scrollView.setBackgroundColor(Color.rgb(0xAA, 0xAA, 0xAA));
    // Finally, display everything
    c.setContentView(scrollView);
    // Screen shouldn't update again
    displayChanged = false;
}

As you can see, both methods (print and updateScreen) work with views and updateScreen also does a setContentView. Now I want to run as much of this code in the AsyncTask background thread. So how much of this code should be in a runOnUiThread(... code here ...)?

Upvotes: 0

Views: 159

Answers (1)

Qw4z1
Qw4z1

Reputation: 3030

You can set displayChanged in a background thread. The rest of the code uses the UI toolkit and accessing this in anything but the UIThread is considered unsafe and not recommended by Google according to the documentation.

Upvotes: 1

Related Questions