我需要从webservice请求数据。我已经实现了以下AsyncTask:
class LoadTagsTask extends AsyncTask<Void, Void, String> {
private String url = "http://webservice.com/rest/tagsManager/search";
ProgressBar loader;
@Override
protected void onPreExecute() {
loader = (ProgressBar) TextsListActivity.this.findViewById(R.id.textLoadingProgressBar);
loader.setVisibility(TextView.VISIBLE);
}
@Override
protected String doInBackground(Void... params) {
HttpURLConnection c = null;
try {
c = (HttpURLConnection) new URL(url).openConnection();
InputStream in = c.getInputStream();
StringBuilder stringBuffer = new StringBuilder();
final char[] charBuffer = new char[8 * 1024];
BufferedReader reader = new BufferedReader(new InputStreamReader(in), charBuffer.length);
int read;
while ((read = reader.read(charBuffer)) != -1) {
stringBuffer.append(charBuffer, 0, read);
}
reader.close();
return stringBuffer.toString();
} catch (Exception e) {
return "";
} finally {
if (c != null) {
c.disconnect();
}
}
}
@Override
protected void onPostExecute(String tags) {
loader.setVisibility(TextView.GONE);
TextsListActivity.this.showTagsSelectorActivity(tags);
}
}
用AsyncTaskLoader
替换它有意义吗?我已经读过它们可以互换使用,但是AsyncTaskLoader
做得更好。是否适用于我的情况?
答案 0 :(得分:4)
我认为您应该将AsyncTask
替换为Retrofit。
它封装了低级逻辑,如管理线程和http连接。
使用Retrofit可以使您的代码更清晰,并且您只需关注后端所服务的数据。
改造支持: