เหตุผลของ ASyncTask แบบ fire-and-forget มีรายละเอียดค่อนข้างดีในคำตอบของ Steve Prentice - อย่างไรก็ตามในขณะที่คุณถูก จำกัดจำนวนครั้งที่คุณดำเนินการ 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 เพียงตัวเดียวยังคงอยู่ในฮีปขณะรันไทม์