【发布时间】:2020-09-27 14:51:19
【问题描述】:
我目前正在自己学习 android,并且对 java 很陌生。我想知道 AsyncTask 是如何工作的:onPreExecute() -> doInBackground() -> onPostExecute()。当我查看其他人定义他们的 AsynTask 时,似乎在他们的代码中只声明了方法,而没有调用该方法。我无法弄清楚doInBackground() 是如何在onPreExecute() 之后出现的,而没有链接两者的代码,例如:
onPreExecute(){ ~~~~~ call doInBackground()}
我的意思是,当AsyncTask.execute() 被调用时,onPreExecute() 被调用,然后是doInBackground(),最后是onPostExecute()。我在库中找不到任何将这些实际连接在一起的代码。我能找到的只有这个:
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
这里当AsyncTask.execute()被调用时,onPreExecute()被调用。但是没有与doInBackground 的任何连接,该任务就可以正常工作。我觉得我缺少 java 或 android 的一些基本逻辑或过程。请帮我解决这个未解决的问题。示例代码如下所示。提前谢谢你。
@Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
@Override
protected String[] doInBackground(String... params) {
/* If there's no zip code, there's nothing to look up. */
if (params.length == 0) {
return null;
}
String location = params[0];
URL weatherRequestUrl = NetworkUtils.buildUrl(location);
try {
String jsonWeatherResponse = NetworkUtils
.getResponseFromHttpUrl(weatherRequestUrl);
String[] simpleJsonWeatherData = OpenWeatherJsonUtils
.getSimpleWeatherStringsFromJson(MainActivity.this, jsonWeatherResponse);
return simpleJsonWeatherData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String[] weatherData) {
// COMPLETED (19) As soon as the data is finished loading, hide the loading indicator
mLoadingIndicator.setVisibility(View.INVISIBLE);
if (weatherData != null) {
// COMPLETED (11) If the weather data was not null, make sure the data view is visible
showWeatherDataView();
/*
* Iterate through the array and append the Strings to the TextView. The reason why we add
* the "\n\n\n" after the String is to give visual separation between each String in the
* TextView. Later, we'll learn about a better way to display lists of data.
*/
for (String weatherString : weatherData) {
mWeatherTextView.append((weatherString) + "\n\n\n");
}
} else {
// COMPLETED (10) If the weather data was null, show the error message
showErrorMessage();
}
【问题讨论】:
标签: java android android-asynctask