我有外部类扩展AsyncTask
以从网站获取字符串以将其解析为JSONObject
或JSONArray
。目前我正在使用方法.get()
来获取结果,但app正在丢弃帧,同时等待服务器响应。我想使用它可重用,因为我从许多不同的类中获取数据。
我的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();
答案 0 :(得分:0)
我想你可以再次阅读document。
执行异步任务时,任务将经历4个步骤: