2016-10-01 83 views
1
@Override 
protected void onPostExecute(String s) { 
    super.onPostExecute(s); 
    asyntask.execute(); 
} 

我正在讀取某些API的數據。是否可以從onPostExecute撥打doInBackground()是否可以從onPostExecute調用doInBackground?

我想遞歸地做5次像(網絡任務和在UI中更新)。提前致謝。

+0

開始你爲什麼要這麼做? –

+0

doInBackground被執行以執行網絡任務,並且在doInBackground之後執行onPostExecute以在doInBackground完成之後使UI改變 –

+0

我想要遞歸地執行5次(網絡任務和在UI中更新)5次,因此調用它是正確的來自onPostexecute的doInbackground。 @ArjunIssar,@蒙面人 –

回答

2

onPostExecute再次開始AsyncTask是一個可怕的想法。正如你想遞歸地做5次網絡調用和UI更新一樣,我想建議你保持一個接口來跟蹤AsyncTask調用。

所以這裏有一個關於如何實現這個行爲的例子。你可以像這樣創建一個interface

public interface MyResponseListener { 
    void myResponseReceiver(String result); 
} 

現在您在AsyncTask類中聲明瞭接口。所以你的AsyncTask可能看起來像這樣。

public class YourAsyncTask extends AsyncTask<Void, Void, String> { 

    // Declare an interface 
    public MyResponseListener myResponse; 

    // Now in your onPostExecute 
    @Override 
    protected void onPostExecute(final String result) { 
     // Send something back to the calling Activity like this to let it know the AsyncTask has finished. 
     myResponse.myResponseReceiver(result); 
    } 
} 

現在你需要實現interface你已經在你的Activity這樣已經創建。你需要的接口引用傳遞到AsyncTask你從你的Activity

public class MainActivity extends Activity implements MyResponseListener { 
    // Your onCreate and other function goes here 

    // Declare an AsyncTask variable first 
    private YourAsyncTask mYourAsyncTask; 

    // Here's a function to start the AsyncTask 
    private startAsyncTask(){ 
     mYourAsyncTask.myResponse = this; 
     // Now start the AsyncTask 
     mYourAsyncTask.execute(); 
    } 

    // You need to implement the function of your interface 
    @Override 
    public void myResponseReceiver(String result) { 
     if(!result.equals("5")) { 
      // You need to keep track here how many times the AsyncTask has been executed. 
      startAsyncTask(); 
     } 
    } 
} 
+0

好的解釋謝謝@Reaz Murshed –

0

AsyncTask類是用來做背景的一些工作並公佈結果給MainThread所以它的一般不可能的,因爲這是在正在開展的工作在MainThread中工作線程可能無法運行(例如,當您在MainThread中進行聯網時,NetworkOnMainThreadException)。 我建議你做一個你的工作數組,並調用AsyncTask的子類的​​方法,它將序列化要在工作線程中完成的工作。

相關問題