如何使用AsyncTask 创建Toast?
@SuppressLint("StaticFieldLeak")
private class RegistrationSuccess extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
return null;
}
@Override
protected void onPreExecute() {
registerButton.setText("注册成功");
// Toast.makeText(Register.this, "注册成功", Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
}
代码中的
Toast.makeText(Register.this, "注册成功", Toast.LENGTH_SHORT).show();
不生效~~~
调用处的代码是OnCreate的一段
new Thread() {
public void run() {
try {
astr = futureTask.get();
Log.e("HelloWorldActivity", astr);
if (astr.equals("OK")) {
Log.e("HelloWorldActivity", astr);
RegistrationSuccess registrationSuccess = new RegistrationSuccess();
registrationSuccess.execute();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();//开启线程
AsyncTask本身就是一种异步,然后你又讲它放入一个线程中,这个时候你在AsyncTask中进行toast显示相当于在子线程中进行更新UI的操作,不闪退已经不错了,
这个解决方案有两种,在启动AsyncTask时直接去掉new Thread(强烈推荐),或者在主线程中创建一个handler,然后在AsyncTask中通过message发送消息至主线程中
的handler中进行toast操作
在线程中更新ui是错误的做法,之所以setText可行是你刚好在校验之前set了,如果你的线程卡顿一下就有可能报错。
无论有没有get方法,你的tread套async一定是错的,修改如下:
将Thread删掉,子线程操作的代码直接挪到async的doInBackground里面即可