2011-01-19 72 views
2

我需要一次一個或全部一次調用web服務5次(因爲有5個不同的參數)。一旦完成了一個特定的調用,在後臺,一個文本視圖應該更新爲文本:「第一完成」,「第二完成」等。Android - 有關AsyncTask的問題

TextView的值應該在後臺更新。

我該怎麼辦?我知道AsyncTask的概念,但我很困惑,應該寫5 AsyncTask,然後爲每個我寫execute()方法來執行AsyncTask?

因爲我在postExecute()方法中設置了「1st completed」,所以我只成功進行了一次調用。但困惑了5次電話。

請給我一個更好的方法或確切的解決方案。

+0

如果Web服務採用相同類型的參數爲5個調用,一個的AsyncTask可以用來創建5異步任務對象,並執行它們,並更新異步任務的TextView的執行後。 – 2011-01-19 09:16:23

回答

11

你只需要1的AsyncTask,你必須做的doInBackground()所有5個電話,每次你完成一個呼叫publishProgress通過例如完成的呼叫的號碼,然後,在年底做任何你在onPostExecute需要。

一個簡單的方法:

private class ServiceCallTask extends AsyncTask<String, Integer, Void> { 

    protected void onPreExecute() { 
     //prepare whatever you need 
     myTextField.setText("starting calls"); 
    } 

    protected Void doInBackground(String... params) { 
     //process params as you need and make the calls 
     doCall1(); 
     publishProgress(1); //this calls onProgressUpdate(1) 
     doCall2(); 
     publishProgress(2); 
     doCall3(); 
     publishProgress(3); 
     doCall4(); 
     publishProgress(4); 
     doCall5(); 
     publishProgress(5); 
     return; 
    } 

    protected void onProgressUpdate(Integer... progress) { 
     //this runs in UI thread so its safe to modify the UI 
     myTextField.append("finished call " + progress); 
    } 

    protected void onPostExecute(Void unused) { 
     myTextField.append("all calls finished"); 
    } 
} 
+0

@ maid450讓我檢查並實施這種方式。 Thanx Thanx Thanx Thanx快速支持。 – 2011-01-19 09:23:07