2014-10-03 91 views
1

如何每15分鐘運行一次這個函數,以便它可以檢查已添加到數據庫的新主題。 我主活動中的一個非常簡單的片段getData()將發送一個HTTP請求到PHP腳本,然後檢索並更新一個TextView,其結果示例是一個簡單的Topic。 現在我想讓這個函數每15分鐘運行一次並將新結果設置爲TextView。如何使用HTTP響應每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()); 
    } 
} 
+1

你爲什麼不直接用onResume();?用戶很少會將應用打開超過15分鐘。如果你必須這樣做,你需要設置一個線程並休眠15分鐘,或者當你更新時獲得時間戳,如果15分鐘已經過去,則在onResume()中運行該函數。 – 2014-10-03 00:09:50

回答

相關問題