2 * Copyright (C) 2011 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package android.support.v2.content;
19 import android.content.Context;
20 import android.os.AsyncTask;
21 import android.os.Handler;
22 import android.os.SystemClock;
23 import android.support.v2.util.TimeUtils;
24 import android.util.Log;
26 import java.io.FileDescriptor;
27 import java.io.PrintWriter;
28 import java.util.concurrent.CountDownLatch;
31 * Static library support version of the framework's {@link android.content.AsyncTaskLoader}.
32 * Used to write apps that run on platforms prior to Android 3.0. When running
33 * on Android 3.0 or above, this implementation is still used; it does not try
34 * to switch to the framework's implementation. See the framework SDK
35 * documentation for a class overview.
37 public abstract class AsyncTaskLoader<D> extends Loader<D> {
38 static final String TAG = "AsyncTaskLoader";
39 static final boolean DEBUG = false;
41 final class LoadTask extends AsyncTask<Void, Void, D> implements Runnable {
46 private CountDownLatch done = new CountDownLatch(1);
48 /* Runs on a worker thread */
50 protected D doInBackground(Void... params) {
51 if (DEBUG) Log.v(TAG, this + " >>> doInBackground");
52 result = AsyncTaskLoader.this.onLoadInBackground();
53 if (DEBUG) Log.v(TAG, this + " <<< doInBackground");
57 /* Runs on the UI thread */
59 protected void onPostExecute(D data) {
60 if (DEBUG) Log.v(TAG, this + " onPostExecute");
62 AsyncTaskLoader.this.dispatchOnLoadComplete(this, data);
69 protected void onCancelled() {
70 if (DEBUG) Log.v(TAG, this + " onCancelled");
72 AsyncTaskLoader.this.dispatchOnCancelled(this, result);
81 AsyncTaskLoader.this.executePendingTask();
85 volatile LoadTask mTask;
86 volatile LoadTask mCancellingTask;
89 long mLastLoadCompleteTime = -10000;
92 public AsyncTaskLoader(Context context) {
97 * Set amount to throttle updates by. This is the minimum time from
98 * when the last {@link #onLoadInBackground()} call has completed until
99 * a new load is scheduled.
101 * @param delayMS Amount of delay, in milliseconds.
103 public void setUpdateThrottle(long delayMS) {
104 mUpdateThrottle = delayMS;
106 mHandler = new Handler();
111 protected void onForceLoad() {
114 mTask = new LoadTask();
115 if (DEBUG) Log.v(TAG, "Preparing load: mTask=" + mTask);
116 executePendingTask();
120 * Attempt to cancel the current load task. See {@link AsyncTask#cancel(boolean)}
121 * for more info. Must be called on the main thread of the process.
123 * <p>Cancelling is not an immediate operation, since the load is performed
124 * in a background thread. If there is currently a load in progress, this
125 * method requests that the load be cancelled, and notes this is the case;
126 * once the background thread has completed its work its remaining state
127 * will be cleared. If another load request comes in during this time,
128 * it will be held until the cancelled load is complete.
130 * @return Returns <tt>false</tt> if the task could not be cancelled,
131 * typically because it has already completed normally, or
132 * because {@link #startLoading()} hasn't been called; returns
133 * <tt>true</tt> otherwise.
135 public boolean cancelLoad() {
136 if (DEBUG) Log.v(TAG, "cancelLoad: mTask=" + mTask);
138 if (mCancellingTask != null) {
139 // There was a pending task already waiting for a previous
140 // one being canceled; just drop it.
141 if (DEBUG) Log.v(TAG,
142 "cancelLoad: still waiting for cancelled task; dropping next");
144 mTask.waiting = false;
145 mHandler.removeCallbacks(mTask);
149 } else if (mTask.waiting) {
150 // There is a task, but it is waiting for the time it should
151 // execute. We can just toss it.
152 if (DEBUG) Log.v(TAG, "cancelLoad: task is waiting, dropping it");
153 mTask.waiting = false;
154 mHandler.removeCallbacks(mTask);
158 boolean cancelled = mTask.cancel(false);
159 if (DEBUG) Log.v(TAG, "cancelLoad: cancelled=" + cancelled);
161 mCancellingTask = mTask;
171 * Called if the task was canceled before it was completed. Gives the class a chance
172 * to properly dispose of the result.
174 public void onCanceled(D data) {
177 void executePendingTask() {
178 if (mCancellingTask == null && mTask != null) {
180 mTask.waiting = false;
181 mHandler.removeCallbacks(mTask);
183 if (mUpdateThrottle > 0) {
184 long now = SystemClock.uptimeMillis();
185 if (now < (mLastLoadCompleteTime+mUpdateThrottle)) {
186 // Not yet time to do another load.
187 if (DEBUG) Log.v(TAG, "Waiting until "
188 + (mLastLoadCompleteTime+mUpdateThrottle)
189 + " to execute: " + mTask);
190 mTask.waiting = true;
191 mHandler.postAtTime(mTask, mLastLoadCompleteTime+mUpdateThrottle);
195 if (DEBUG) Log.v(TAG, "Executing: " + mTask);
196 mTask.execute((Void[]) null);
197 // XXX TO DO: use reflection to call this version.
198 //mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
202 void dispatchOnCancelled(LoadTask task, D data) {
204 if (mCancellingTask == task) {
205 if (DEBUG) Log.v(TAG, "Cancelled task is now canceled!");
206 mLastLoadCompleteTime = SystemClock.uptimeMillis();
207 mCancellingTask = null;
208 executePendingTask();
212 void dispatchOnLoadComplete(LoadTask task, D data) {
214 if (DEBUG) Log.v(TAG, "Load complete of old task, trying to cancel");
215 dispatchOnCancelled(task, data);
218 // This cursor has been abandoned; just cancel the new data.
221 mLastLoadCompleteTime = SystemClock.uptimeMillis();
223 if (DEBUG) Log.v(TAG, "Delivering result");
231 public abstract D loadInBackground();
234 * Called on a worker thread to perform the actual load. Implementations should not deliver the
235 * result directly, but should return them from this method, which will eventually end up
236 * calling {@link #deliverResult} on the UI thread. If implementations need to process
237 * the results on the UI thread they may override {@link #deliverResult} and do so
240 * @return Implementations must return the result of their load operation.
242 protected D onLoadInBackground() {
243 return loadInBackground();
247 * Locks the current thread until the loader completes the current load
248 * operation. Returns immediately if there is no load operation running.
249 * Should not be called from the UI thread: calling it from the UI
250 * thread would cause a deadlock.
252 * Use for testing only. <b>Never</b> call this from a UI thread.
256 public void waitForLoader() {
257 LoadTask task = mTask;
261 } catch (InterruptedException e) {
268 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
269 super.dump(prefix, fd, writer, args);
271 writer.print(prefix); writer.print("mTask="); writer.print(mTask);
272 writer.print(" waiting="); writer.println(mTask.waiting);
274 if (mCancellingTask != null) {
275 writer.print(prefix); writer.print("mCancellingTask="); writer.print(mCancellingTask);
276 writer.print(" waiting="); writer.println(mCancellingTask.waiting);
278 if (mUpdateThrottle != 0) {
279 writer.print(prefix); writer.print("mUpdateThrottle=");
280 TimeUtils.formatDuration(mUpdateThrottle, writer);
281 writer.print(" mLastLoadCompleteTime=");
282 TimeUtils.formatDuration(mLastLoadCompleteTime,
283 SystemClock.uptimeMillis(), writer);