ASyncTask के आग-और-भुलाने के कारणों के कारण स्टीव प्रेंटिस के जवाब में बहुत अच्छी तरह से विस्तृत हैं - हालाँकि, जब तक आप कितनी बार आप ASyncTask को निष्पादित करते हैं, इस पर प्रतिबंधित है , तो आप वह काम करने के लिए स्वतंत्र हैं, जब आप धागा पसंद करते हैं। ।
अपने निष्पादन योग्य कोड को doInBackground () के भीतर एक लूप के अंदर रखें और प्रत्येक निष्पादन को ट्रिगर करने के लिए एक समवर्ती लॉक का उपयोग करें। आप publishProgress () / onProgressUpdate () का उपयोग करके परिणाम प्राप्त कर सकते हैं ।
उदाहरण:
class GetDataFromServerTask extends AsyncTask<Input, Result, Void> {
private final ReentrantLock lock = new ReentrantLock();
private final Condition tryAgain = lock.newCondition();
private volatile boolean finished = false;
@Override
protected Void doInBackground(Input... params) {
lock.lockInterruptibly();
do {
// This is the bulk of our task, request the data, and put in "result"
Result result = ....
// Return it to the activity thread using publishProgress()
publishProgress(result);
// At the end, we acquire a lock that will delay
// the next execution until runAgain() is called..
tryAgain.await();
} while(!finished);
lock.unlock();
}
@Override
protected void onProgressUpdate(Result... result)
{
// Treat this like onPostExecute(), do something with result
// This is an example...
if (result != whatWeWant && userWantsToTryAgain()) {
runAgain();
}
}
public void runAgain() {
// Call this to request data from the server again
tryAgain.signal();
}
public void terminateTask() {
// The task will only finish when we call this method
finished = true;
lock.unlock();
}
@Override
protected void onCancelled() {
// Make sure we clean up if the task is killed
terminateTask();
}
}
बेशक, यह ASyncTask के पारंपरिक उपयोग की तुलना में थोड़ा अधिक जटिल है, और आप वास्तविक प्रगति रिपोर्टिंग के लिए publishProgress () का उपयोग छोड़ देते हैं । लेकिन यदि स्मृति आपकी चिंता है, तो यह दृष्टिकोण रनटाइम के दौरान ढेर में केवल एक ASyncTask बनी रहेगी।