UI线程中应该有多少代码?

时间:2015-06-01 10:30:31

标签: java android multithreading android-asynctask

所以我有AsyncTask在后​​台做一些工作。这项工作实际上是一个在for循环中完成的命令列表。所有命令都可以运行以下方法(在for循环中):

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;
}

在for循环结束时,我有这一行:

if (displayChanged) updateScreen();

最后是updateScreen()方法:

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;
}

正如您所看到的,两种方法(printupdateScreen)都可以使用视图,updateScreen也可以使用setContentView。现在我想在AsyncTask后台线程中运行尽可能多的代码。那么这段代码中有多少应该是runOnUiThread(... code here ...)

1 个答案:

答案 0 :(得分:1)

您可以在后台线程中设置displayChanged。其余代码使用UI工具包并在任何内容中访问它,但UIThread被认为是不安全的,Google不推荐根据the documentation