嘿所有我正在编写一个android应用程序,它从node.js服务器获取一个JSON对象。我的代码如下(我无法访问服务器代码)。有没有办法一致地检查服务器是否有JSON对象的更改(如果他们更新它)?现在它只做一次GET并停止。我希望能够查询更改并继续使用新更新。思考?感谢。
从OnCreate()调用:
new Read().execute("JSONkey");
这是我的Read ASyncTask:
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;
}
}
答案 0 :(得分:1)
执行此操作的正确方法是使用WebSocket但是由于无法控制服务器端的限制,最好的选择是
将您的代码放入服务中:
http://developer.android.com/reference/android/app/IntentService.html
然后使用警报管理器安排定期更新。
http://developer.android.com/reference/android/app/AlarmManager.html