2016-10-01 86 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的子类的​​方法,它将序列化要在工作线程中完成的工作。

相关问题