以下代码有很多问题,但没有错误并显示/给出。
这里发生了什么?
public class TestApp1Activity extends Activity {
private static final String TAG = TestApp1Activity.class.getSimpleName();
private Button btn1, btn2, btn3;
private ExecutorService threadPool;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button2);
threadPool = Executors.newFixedThreadPool(4);
threadPool.submit(new Runnable() {
@Override
public void run() {
btn3.setText("fud"); // should give a NullPointerException. Doesn't only stops execution.
btn2.setText("From pool"); // shouldn't be able to touch UI comps from non-UI thread
}
});
new Thread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "Before setting text on btn");
btn1.setText("From thread"); // shouldn't be able to touch UI comps from non-UI thread
Log.i(TAG, "After setting text on btn");
// So below actually throws the error I wanted.
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.cox1);
imageView.setImageBitmap(bm);
}
}).start();
}
}
编辑:由于我得到了错误的答案,让我回答我自己的问题。
答案 0 :(得分:2)
1)ExecutorService.submit将runnable包装在try / catch中。如果抛出任何错误,则会被悄然丢弃。这是非常糟糕的设计。永远不应该悄悄地压制错误。
2)所以显然你可以从另一个线程修改一些视图组件。只是不是全部。该组件只是设置它的属性,在下一个onDraw上重新绘制组件。你可以用很多组件实现这一点,但Android团队说“你可能会得到意想不到的结果。”所以避免它。