【发布时间】:2017-02-22 01:54:18
【问题描述】:
我有扩展AsyncTask 的外部类从网站获取字符串以将其解析为JSONObject 或JSONArray。目前我正在使用方法.get() 来获取结果,但是应用程序正在丢帧,同时等待服务器响应。我想使用它可重用,因为我从许多不同的类中获取数据。
我的 Asynctask 类:
public class JsonTask extends AsyncTask<String, String, String> {
protected String doInBackground(String...params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
Log.d("Response: ", "> Establishing Connection" );
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}}
现在我通过以下方式获取数据:
String result = new JsonTask().execute(url).get();
【问题讨论】:
-
@RichArt - 可能是因为
AsyncTask.execute()返回异步任务实例本身,而不是String或任何其他类型的结果。
标签: java android json multithreading android-asynctask