这是我的示例代码。
public class test extends Activity {
private TextView tv;
public class Blap extends AsyncTask<String,String,Boolean>{
private test parent;
@Override
protected Boolean doInBackground(String... options) {
this.auth(options[0],options[1]);
parent.aresponse(res);
return true;
}
public Blap(test a){
this.parent = a;
}
public auth(String login, String password){
//process auth
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
//work...
}
public void buttonclick(View v){
tv = new TextView(this);
new Blap(this).execute(editText1.getText().toString(),editText2.getText().toString());
setContentView(tv);
}
public void aresponse(String rs){
tv.setText(rs);
}
}
但是当调用 aresponse 时,我得到一个异常:只有创建 View 层次结构的原始线程才能触及它的 View 。 如何正确等待异步操作完成并继续处理所需的操作?
最佳答案
AsyncTask
为您提供两种更新 UI 的可能性:
如果您想在 doInBackground()
中执行的任务的同时更新 UI (例如更新 ProgressBar
),你必须调用 publishProgress()
在doInBackground()
里面方法。然后您必须更新 onProgressUpdate()
中的 UI方法。
如果你想在任务完成后更新用户界面,你必须在 onPostExecute()
中进行方法。
/** This method runs on another thread than the UI thread */
@Override
protected String doInBackground(String... _params) {
for (int progressValue = 0; progressValue < 100; progressValue++) {
publishProgress(progressValue);
}
}
/** This method runs on the UI thread */
@Override
protected void onProgressUpdate(Integer... progressValue) {
// TODO Update your ProgressBar here
}
/**
* Called after doInBackground() method
* This method runs on the UI thread
*/
@Override
protected void onPostExecute(Boolean _result) {
// TODO Update the UI thread with the final result
}
在您的情况下,您应该使用 AsyncTask<String, String, String>
因为你需要doInBackground()
返回一个字符串。然后你只需要处理 onPostExecute()
中的结果
public class test extends Activity {
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
//work...
}
public void buttonclick(View v){
tv = new TextView(this);
new Blap().execute(editText1.getText().toString(), editText2.getText().toString());
setContentView(tv);
}
public class Blap extends AsyncTask<String, String, String> {
private test parent;
@Override
protected String doInBackground(String... options) {
this.auth(options[0], options[1]);
String result = "my result";
return result;
}
public auth(String login, String password){
//process auth
}
@Override
protected void onPostExecute(String _result) {
tv.setText(_result);
}
}
}
关于java - 如何从 AsyncTask 中的回调函数访问父类 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10316335/