[英]How to define a callback for when an AsyncTask completes
I have an Android fragment which requests a web page using an AsyncTask and retrieves the page title which should be displayed in a TextView.我有一个 Android 片段,它使用 AsyncTask 请求 web 页面并检索应显示在 TextView 中的页面标题。 I invoke the AsyncTask in onCreateView().
我在 onCreateView() 中调用 AsyncTask。
The problem is there is a noticiable delay before the AsyncTask completes and the fragment view is created and displayed.问题是在 AsyncTask 完成以及创建和显示片段视图之前存在明显的延迟。
The code is as follows:代码如下:
GetWebsiteAsyncTask getWebsiteAsyncTask = new GetWebsiteAsyncTask();
String websiteTitle = getWebsiteAsyncTask.execute().get();
websiteViewModel.setTitle(websiteTitle);
With the AsyncTask defined as:将 AsyncTask 定义为:
class GetWebsiteAsyncTask extends AsyncTask<Void, Void, String> {
private static final String TAG = GetWebsiteAsyncTask.class.getName();
@Override
protected String doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://www.google.com").get();
return doc.title();
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
return null;
}
}
Following Selvin's advice in the comment I have modified the code to use a callback delegate in the AsyncTask as follows:按照 Selvin 在评论中的建议,我修改了代码以在 AsyncTask 中使用回调委托,如下所示:
1. 1.
public interface AsyncResponse {
void processFinish(String output);
}
class GetWebsiteAsyncTask extends AsyncTask<Void, Void, String> {
public AsyncResponse delegate = null;
@Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
public class WebsiteFragment extends Fragment implements AsyncResponse
GetWebsiteAsyncTask getWebsiteAsyncTask = new GetWebsiteAsyncTask();
getWebsiteAsyncTask.delegate = this;
getWebsiteAsyncTask.execute();
@Override
public void processFinish(String output) {
websiteViewModel.setTitle(output);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.