我正在使用developer.android.com中的代码来阅读网站,但我不了解如何在myClickHandler
方法中访问数据。该程序可以正常工作并获取数据,但我只能在DownloadWebpageTask
类中看到它。这是代码部分:
那么在myClickHandler
中我可以访问onPostExecute
生成的数据吗?谢谢你的帮助。
public class HttpExampleActivity extends Activity {
private static final String DEBUG_TAG = "HttpExample";
private EditText urlText;
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
urlText = (EditText) findViewById(R.id.myUrl);
textView = (TextView) findViewById(R.id.myText);
}
public void myClickHandler(View view) {
// Gets the URL from the UI's text field.
String stringUrl = urlText.getText().toString();
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
...
}
答案 0 :(得分:0)
访问此处:http://developer.android.com/reference/android/os/AsyncTask.html以了解有关异步任务的更多信息。
对于你的问题:我可以访问onPostExecute产生的数据吗? Ans:是的,您可以访问onPostExecute,因为它在doInBackground之后在UI线程上运行。
onPostExecute是否必须等待doInBackground完成? 答:是的
AsyncTask有四个步骤:
onPreExecute:在调用doInBackground方法之前调用此方法。
onProgressUpdate:通过从doInBackground调用此方法调用publishProgress来调用此方法