FileDocCategorySizeDatePackage
AsyncTaskLoader.javaAPI DocAndroid 5.1 API14070Thu Mar 12 22:22:10 GMT 2015android.content

AsyncTaskLoader

public abstract class AsyncTaskLoader extends Loader
Abstract Loader that provides an {@link AsyncTask} to do the work. See {@link Loader} and {@link android.app.LoaderManager} for more details.

Here is an example implementation of an AsyncTaskLoader subclass that loads the currently installed applications from the package manager. This implementation takes care of retrieving the application labels and sorting its result set from them, monitoring for changes to the installed applications, and rebuilding the list when a change in configuration requires this (such as a locale change). {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LoaderCustom.java loader}

An example implementation of a fragment that uses the above loader to show the currently installed applications in a list is below. {@sample development/samples/ApiDemos/src/com/example/android/apis/app/LoaderCustom.java fragment}

param
the data type to be loaded.

Fields Summary
static final String
TAG
static final boolean
DEBUG
private final Executor
mExecutor
volatile LoadTask
mTask
volatile LoadTask
mCancellingTask
long
mUpdateThrottle
long
mLastLoadCompleteTime
android.os.Handler
mHandler
Constructors Summary
public AsyncTaskLoader(Context context)


       
        this(context, AsyncTask.THREAD_POOL_EXECUTOR);
    
public AsyncTaskLoader(Context context, Executor executor)
{@hide}

        super(context);
        mExecutor = executor;
    
Methods Summary
public voidcancelLoadInBackground()
Called on the main thread to abort a load in progress. Override this method to abort the current invocation of {@link #loadInBackground} that is running in the background on a worker thread. This method should do nothing if {@link #loadInBackground} has not started running or if it has already finished.

see
#loadInBackground

    
voiddispatchOnCancelled(android.content.AsyncTaskLoader$LoadTask task, D data)

        onCanceled(data);
        if (mCancellingTask == task) {
            if (DEBUG) Log.v(TAG, "Cancelled task is now canceled!");
            rollbackContentChanged();
            mLastLoadCompleteTime = SystemClock.uptimeMillis();
            mCancellingTask = null;
            if (DEBUG) Log.v(TAG, "Delivering cancellation");
            deliverCancellation();
            executePendingTask();
        }
    
voiddispatchOnLoadComplete(android.content.AsyncTaskLoader$LoadTask task, D data)

        if (mTask != task) {
            if (DEBUG) Log.v(TAG, "Load complete of old task, trying to cancel");
            dispatchOnCancelled(task, data);
        } else {
            if (isAbandoned()) {
                // This cursor has been abandoned; just cancel the new data.
                onCanceled(data);
            } else {
                commitContentChanged();
                mLastLoadCompleteTime = SystemClock.uptimeMillis();
                mTask = null;
                if (DEBUG) Log.v(TAG, "Delivering result");
                deliverResult(data);
            }
        }
    
public voiddump(java.lang.String prefix, java.io.FileDescriptor fd, java.io.PrintWriter writer, java.lang.String[] args)

        super.dump(prefix, fd, writer, args);
        if (mTask != null) {
            writer.print(prefix); writer.print("mTask="); writer.print(mTask);
                    writer.print(" waiting="); writer.println(mTask.waiting);
        }
        if (mCancellingTask != null) {
            writer.print(prefix); writer.print("mCancellingTask="); writer.print(mCancellingTask);
                    writer.print(" waiting="); writer.println(mCancellingTask.waiting);
        }
        if (mUpdateThrottle != 0) {
            writer.print(prefix); writer.print("mUpdateThrottle=");
                    TimeUtils.formatDuration(mUpdateThrottle, writer);
                    writer.print(" mLastLoadCompleteTime=");
                    TimeUtils.formatDuration(mLastLoadCompleteTime,
                            SystemClock.uptimeMillis(), writer);
                    writer.println();
        }
    
voidexecutePendingTask()

        if (mCancellingTask == null && mTask != null) {
            if (mTask.waiting) {
                mTask.waiting = false;
                mHandler.removeCallbacks(mTask);
            }
            if (mUpdateThrottle > 0) {
                long now = SystemClock.uptimeMillis();
                if (now < (mLastLoadCompleteTime+mUpdateThrottle)) {
                    // Not yet time to do another load.
                    if (DEBUG) Log.v(TAG, "Waiting until "
                            + (mLastLoadCompleteTime+mUpdateThrottle)
                            + " to execute: " + mTask);
                    mTask.waiting = true;
                    mHandler.postAtTime(mTask, mLastLoadCompleteTime+mUpdateThrottle);
                    return;
                }
            }
            if (DEBUG) Log.v(TAG, "Executing: " + mTask);
            mTask.executeOnExecutor(mExecutor, (Void[]) null);
        }
    
public booleanisLoadInBackgroundCanceled()
Returns true if the current invocation of {@link #loadInBackground} is being canceled.

return
True if the current invocation of {@link #loadInBackground} is being canceled.
see
#loadInBackground

        return mCancellingTask != null;
    
public abstract DloadInBackground()
Called on a worker thread to perform the actual load and to return the result of the load operation. Implementations should not deliver the result directly, but should return them from this method, which will eventually end up calling {@link #deliverResult} on the UI thread. If implementations need to process the results on the UI thread they may override {@link #deliverResult} and do so there. To support cancellation, this method should periodically check the value of {@link #isLoadInBackgroundCanceled} and terminate when it returns true. Subclasses may also override {@link #cancelLoadInBackground} to interrupt the load directly instead of polling {@link #isLoadInBackgroundCanceled}. When the load is canceled, this method may either return normally or throw {@link OperationCanceledException}. In either case, the {@link Loader} will call {@link #onCanceled} to perform post-cancellation cleanup and to dispose of the result object, if any.

return
The result of the load operation.
throws
OperationCanceledException if the load is canceled during execution.
see
#isLoadInBackgroundCanceled
see
#cancelLoadInBackground
see
#onCanceled

protected booleanonCancelLoad()

        if (DEBUG) Log.v(TAG, "onCancelLoad: mTask=" + mTask);
        if (mTask != null) {
            if (mCancellingTask != null) {
                // There was a pending task already waiting for a previous
                // one being canceled; just drop it.
                if (DEBUG) Log.v(TAG,
                        "cancelLoad: still waiting for cancelled task; dropping next");
                if (mTask.waiting) {
                    mTask.waiting = false;
                    mHandler.removeCallbacks(mTask);
                }
                mTask = null;
                return false;
            } else if (mTask.waiting) {
                // There is a task, but it is waiting for the time it should
                // execute.  We can just toss it.
                if (DEBUG) Log.v(TAG, "cancelLoad: task is waiting, dropping it");
                mTask.waiting = false;
                mHandler.removeCallbacks(mTask);
                mTask = null;
                return false;
            } else {
                boolean cancelled = mTask.cancel(false);
                if (DEBUG) Log.v(TAG, "cancelLoad: cancelled=" + cancelled);
                if (cancelled) {
                    mCancellingTask = mTask;
                    cancelLoadInBackground();
                }
                mTask = null;
                return cancelled;
            }
        }
        return false;
    
public voidonCanceled(D data)
Called if the task was canceled before it was completed. Gives the class a chance to clean up post-cancellation and to properly dispose of the result.

param
data The value that was returned by {@link #loadInBackground}, or null if the task threw {@link OperationCanceledException}.

    
protected voidonForceLoad()

        super.onForceLoad();
        cancelLoad();
        mTask = new LoadTask();
        if (DEBUG) Log.v(TAG, "Preparing load: mTask=" + mTask);
        executePendingTask();
    
protected DonLoadInBackground()
Calls {@link #loadInBackground()}. This method is reserved for use by the loader framework. Subclasses should override {@link #loadInBackground} instead of this method.

return
The result of the load operation.
throws
OperationCanceledException if the load is canceled during execution.
see
#loadInBackground

        return loadInBackground();
    
public voidsetUpdateThrottle(long delayMS)
Set amount to throttle updates by. This is the minimum time from when the last {@link #loadInBackground()} call has completed until a new load is scheduled.

param
delayMS Amount of delay, in milliseconds.

        mUpdateThrottle = delayMS;
        if (delayMS != 0) {
            mHandler = new Handler();
        }
    
public voidwaitForLoader()
Locks the current thread until the loader completes the current load operation. Returns immediately if there is no load operation running. Should not be called from the UI thread: calling it from the UI thread would cause a deadlock.

Use for testing only. Never call this from a UI thread.

hide

        LoadTask task = mTask;
        if (task != null) {
            task.waitForLoader();
        }