我的应用程序结合了在自己的线程上运行的 SurfaceView 和在主应用程序线程上运行的一堆常规视图。在大多数情况下,这工作正常。但是,当我尝试让 SurfaceView 的线程上的某些内容触发对主应用程序线程中的 UI 元素之一的更改时,我得到了 android.View.ViewRoot$CalledFromWrongThreadException。
有没有解决这个问题的正确方法?我应该使用异步任务吗?运行线程()?或者将自己线程上的 SurfaceView 与主线程上的其他 UI 元素混合只是天生的坏事?
如果我的问题没有意义,这里的伪代码可能更清楚。
// Activity runs on main application thread
public class MainActivity extends Activity {
RelativeLayout layout;
TextView popup;
MySurfaceView mysurfaceview;
protected void onCreate(Bundle savedInstanceState) {
...
setContentView(layout);
layout.addView(mysurfaceview); // Surface View is displayed
popup.setText("You won"); // created but not displayed yet
}
public void showPopup() {
layout.addView(popup);
}
}
// Surface View runs on its own separate thread
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, OnTouchListener {
private ViewThread mThread;
public boolean onTouch(View v, MotionEvent event) {
...
if (someCondition == true) {
mainactivity.showPopup();
// This works because onTouch() is called by main app thread
}
}
public void Draw(Canvas canvas) {
...
if (someCondition == true) {
mainactivity.showPopup();
// This crashes with ViewRoot$CalledFromWrongThreadException
// because Draw is called by mThread
// Is this fixable?
}
}
}