【发布时间】:2010-11-09 15:41:56
【问题描述】:
所以,我收到一个错误,我从错误的线程更新 UI。这当然不是我的本意。我的案例很长,但我会尽量用代码 sn-ps 来做到这一点。我的最终目标是在一个单独的线程中运行一项昂贵的任务,并将沿途发生的更新发布到我的 listView 的末尾。
public class test extends Activity {
private ArrayAdapter<String> _mOutArrayAdapter;
private ListView _mOutView;
private EditText _mCmdEditText;
private Button _mRunButton;
private Interpreter _interpreter;
// Need handler for callbacks to the UI thread
public final Handler _mHandler = new Handler() {
public void handleMessage(Message msg) {
_mOutArrayAdapter.add(msg.getData().getString("text"));
};
};
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
updateResultsInUi();
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_interpreter = new Interpreter(true);
_mOutView = (ListView)findViewById(R.id.out);
_mCmdEditText = (EditText)findViewById(R.id.edit_command);
_mRunButton = (Button)findViewById(R.id.button_run);
_mOutArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
_mOutView.setAdapter(_mOutArrayAdapter);
_mOutArrayAdapter.clear();
_interpreter.setOutputAdapter(_mOutArrayAdapter);
Thread t = new Thread() {
public void run() {
_mResults = _interpreter.executeExpression("startup;",_mHandler);
_mHandler.post(mUpdateResults);
}
};
t.start();
);
然后在解释器中我这样做:
public class Interpreter
{
private static Handler _mHandler;
public String executeExpression(String expression, Handler handler)
{
_mHandler = handler;
//Do a bunch of stuff that sometimes calls displayText from this class or from others
return answer;
}
public void displayText(String text)
{
Message msg = new Message();
Bundle bndl = new Bundle();
bndl.putString("text", text);
msg.setData(bndl);
_mHandler.dispatchMessage(msg);
}
}
最终答案的显示有效。并且 dispatchMessage 最终触发了 handleMessage,但它抛出了一个错误,我无法从 UI 线程之外修改 UI,我知道这是非法的。那么,我做错了什么?
谢谢!
【问题讨论】:
-
尝试使用异步任务,正如其他人所说,不确定您的代码在做什么
-
你是对的,sendMessage是用来发送handler的handleMessage中接收到的消息。