【发布时间】:2014-06-19 16:05:32
【问题描述】:
大家好,我正在编写一个从 node.js 服务器获取 JSON 对象的 android 应用程序。我的代码如下(我无权访问服务器代码)。有什么方法可以持续检查服务器是否有 JSON 对象的更改(如果他们更新它)?现在它只执行一次 GET 并停止。我希望能够查询更改并继续使用新更新。想法?谢谢。
从 OnCreate() 调用:
new Read().execute("JSONkey");
这是我的读取异步任务:
public class Read extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String...param) {
try {
read_json = getCoords();
httpText.append(read_json.toString() + "\n");
try{
}catch(Exception e){ e.printStackTrace(); }
JSONArray data = read_json.getJSONArray(param[0]);
for (int i = 0; i < data.length(); ++i){
JSONObject info = data.getJSONObject(i);
Coordinate pt = new Coordinate(info.getInt("point"), info.getString("name"), info.getDouble("lat"), info.getDouble("long"));
coords.put(pt.getPoint(), pt);
coordList.add(new GeoPoint(pt.getLat(),pt.getLong()));
}
return "Success"; //get "text"
} catch (Exception e){
return "Fail";
}
}
@Override
protected void onPostExecute(String result){
//Doing something with JSON
//new Read().execute("coords"); tried doing this, but I feel it is not right.
}
}
和 GetCoords():
public JSONObject getCoords()
throws ClientProtocolException, IOException, JSONException{
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject last = new JSONObject(data);
return last;
}else{
return null;
}
}
【问题讨论】:
-
我会推荐使用套接字甚至更好的 gcm。不断轮询服务器会极大地影响服务器和手机电池
标签: java android json get httprequest