我如何每隔15分钟运行一次这个函数,这样它就可以检查是否有新的Topic添加到数据库中。我在mainactivity中有一个非常简单的片段getData(),它将向PHP脚本发送HTTP请求,然后检索并更新TextView,结果示例为一个简单的Topic。现在我想让这个函数每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());
}
}
Dave S提供的我自己的问题的答案。刷新活动OnResume();使用onResume()刷新活动