【问题标题】:Continuous connection via HttpGet?通过 HttpGet 持续连接?
【发布时间】: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


【解决方案1】:

做到这一点的正确方法是使用 WebSocket,但考虑到无法控制服务器端的限制,最好的选择是

将您的代码放入服务中:

http://developer.android.com/reference/android/app/IntentService.html

然后使用警报管理器安排定期更新。

http://developer.android.com/reference/android/app/AlarmManager.html

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2017-06-10
    • 2017-10-12
    相关资源
    最近更新 更多