是否可以从onPostExecute调用doInBackground?
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
asyntask.execute();
}
我正在读取某些API的数据。是否可以从onPostExecute
拨打doInBackground()
?是否可以从onPostExecute调用doInBackground?
我想递归地做5次像(网络任务和在UI中更新)。提前致谢。
从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();
}
}
}
好的解释谢谢@Reaz Murshed –
doInBackground()在调用onPostExecute之前调用。
由于您无法在UI线程上执行网络任务,因此会创建一个AsyncTask。 AsyncTask在后台执行,在工作线程上执行网络任务。然后,在完成后台任务后,将调用onPostExecute(),以便在UI线程上更改UI。
这应有助于:https://developer.android.com/reference/android/os/AsyncTask.html
https://developer.android.com/training/basics/network-ops/index.html
的AsyncTask
类是用来做背景的一些工作并公布结果给MainThread
所以它的一般不可能的,因为这是在正在开展的工作在MainThread
中工作线程可能无法运行(例如,当您在MainThread
中进行联网时,NetworkOnMainThreadException
)。 我建议你做一个你的工作数组,并调用AsyncTask
的子类的方法,它将序列化要在工作线程中完成的工作。
开始你为什么要这么做? –
doInBackground被执行以执行网络任务,并且在doInBackground之后执行onPostExecute以在doInBackground完成之后使UI改变 –
我想要递归地执行5次(网络任务和在UI中更新)5次,因此调用它是正确的来自onPostexecute的doInbackground。 @ArjunIssar,@蒙面人 –