2013-11-27 36 views
2

我正在編寫一個程序,它從互聯網獲取貨幣價格,並將此代碼放在一個asynctask中。我需要能夠獲得持續的更新,但我不太確定循環的asynctask而不會搞亂程序。任何幫助感謝!Android中的AsyncTask循環

我需要這個代碼連續運行:

public void parseJSON(){ 
     new AsyncTask<Void, Void, String>() { 
      protected String doInBackground(Void... params) { 

       try { 
        return downloadJSON(ticker); 
       } catch (Exception e) { 
        Log.d("JWP", e.toString()); 
       } 

       return "Can't reach server. Is Internet access enabled?"; 
      } 

      @Override 
      protected void onProgressUpdate(Void... values) { 
       TextView textView = (TextView) findViewById(R.id.ltcdata); 

       textView.setText("Retrieving Data..."); 
      } 

      @Override 
      protected void onPostExecute(String result) { 
       TextView textView = (TextView) findViewById(R.id.ltcdata); 

       try { 
        JSONObject items = (JSONObject) new JSONTokener(result) 
          .nextValue(); 

        String price = items.getJSONObject("ticker").getString(
          "last"); 
        String high = items.getJSONObject("ticker").getString(
          "high"); 
        String low = items.getJSONObject("ticker").getString("low"); 

        textView.append("Last Price: $" + price + "\n"); 
        textView.append("High: $" + high + "\n"); 
        textView.append("Low: $" + low + "\n"); 

       } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      } 

     }.execute(); 
    } 

回答

1

使用定時器處理程序執行異步任務。在下面的例子中,它將每5秒連續檢查一次。

private Handler handler = new Handler(); 


private Runnable runnable = new Runnable() { 

public void run() { 

    parseJSON(); 

    /* 
    * Now register it for running next time 
    */ 

    handler.postDelayed(this, 5000); // the request will be made again 5 sec later 
} 


}; 

使用runnable.run();啓動定時器和runnable.removeCallbacks(handler);停止它。

+0

謝謝。這解決了我的問題。 – Omid1989

0

創建調用您的asynctask函數的函數,並在asynctask函數內調用調用您的asynctask的函數。

打電話給你的asynctask();

public void callasynctask(){ 
    parseJSON(); 
    } 

parseJSON內部();

public void parseJSON(){ 

. 
. 
. 
. 
. 
. 
    } 

     }.execute(); 
callasynctask() 
} 
0

使用以指定時間間隔執行的線程並在該線程中調用此異步任務。