@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
asyntask.execute();
}
我正在讀取某些API的數據。是否可以從onPostExecute
撥打doInBackground()
?是否可以從onPostExecute調用doInBackground?
我想遞歸地做5次像(網絡任務和在UI中更新)。提前致謝。
@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,@蒙面人 –