【问题标题】:How To Update an TextView with an HTTP response every 15 minutes?如何每 15 分钟使用 HTTP 响应更新 TextView?
【发布时间】:2014-10-03 00:06:27
【问题描述】:

我如何运行这个函数说每 15 分钟一次,以便它可以检查已添加到数据库中的新主题。 我在 mainactivity 中有一个非常简单的 sn-p getData(),它将向 PHP 脚本发送 HTTP 请求,然后检索和更新 TextView,结果示例是一个简单的主题。 现在我想让这个函数每 15 分钟运行一次,并将新结果设置为 TextView。

public void getData() {
    String result = "";
    InputStream isr = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(""); //YOUR PHP SCRIPT ADDRESS
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
        topic.setText("Couldnt connect to database");
    }
    //convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();

        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    //parse json data
    try {
        String n = "";

        JSONArray jArray = new JSONArray(result);

        JSONObject json = jArray.getJSONObject(0);
        n = n + "Topic: " + json.getString("Topic") + "\n";
        topic.setText(n);
    } catch (Exception e) {
        Log.e("log_tag", "Error Parsing Data " + e.toString());
    }
}

【问题讨论】:

  • 你为什么不在 onResume(); 上做呢?用户很少将应用程序打开超过 15 分钟。如果必须这样做,则需要设置一个线程并休眠 15 分钟,或者在更新时获取时间戳,如果 15 分钟过去,则在 onResume() 中运行该函数。

标签: android json http android-studio


【解决方案1】:

回答 Dave S 提供的我自己的问题。 刷新活动 OnResume(); Using onResume() to refresh activity

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 2011-04-25
    相关资源
    最近更新 更多