PageRenderTime 30ms CodeModel.GetById 12ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 1ms

/utils/src/com/google/marvin/utils/UserTask.java

http://eyes-free.googlecode.com/
Java | 459 lines | 159 code | 39 blank | 261 comment | 4 complexity | 66d8a0c40f034b0feb5fc91f9e8b294d MD5 | raw file
  1/*
  2 * Copyright (C) 2008 Google Inc.
  3 *
  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
  7 *
  8 *      http://www.apache.org/licenses/LICENSE-2.0
  9 *
 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.
 15 */
 16
 17// Taken from the Photostream app by Romain Guy 
 18// at http://apps-for-android.googlecode.com
 19package com.google.marvin.utils;
 20
 21import android.os.*;
 22import android.os.Process;
 23
 24import java.util.concurrent.ThreadPoolExecutor;
 25import java.util.concurrent.TimeUnit;
 26import java.util.concurrent.BlockingQueue;
 27import java.util.concurrent.LinkedBlockingQueue;
 28import java.util.concurrent.ThreadFactory;
 29import java.util.concurrent.Callable;
 30import java.util.concurrent.FutureTask;
 31import java.util.concurrent.ExecutionException;
 32import java.util.concurrent.TimeoutException;
 33import java.util.concurrent.CancellationException;
 34import java.util.concurrent.atomic.AtomicInteger;
 35
 36/**
 37 * <p>UserTask enables proper and easy use of the UI thread. This class allows to
 38 * perform background operations and publish results on the UI thread without
 39 * having to manipulate threads and/or handlers.</p>
 40 *
 41 * <p>A user task is defined by a computation that runs on a background thread and
 42 * whose result is published on the UI thread. A user task is defined by 3 generic
 43 * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
 44 * and 4 steps, called <code>begin</code>, <code>doInBackground</code>,
 45 * <code>processProgress<code> and <code>end</code>.</p>
 46 *
 47 * <h2>Usage</h2>
 48 * <p>UserTask must be subclassed to be used. The subclass will override at least
 49 * one method ({@link #doInBackground(Object[])}), and most often will override a
 50 * second one ({@link #onPostExecute(Object)}.)</p>
 51 *
 52 * <p>Here is an example of subclassing:</p>
 53 * <pre>
 54 * private class DownloadFilesTask extends UserTask&lt;URL, Integer, Long&gt; {
 55 *     public File doInBackground(URL... urls) {
 56 *         int count = urls.length;
 57 *         long totalSize = 0;
 58 *         for (int i = 0; i < count; i++) {
 59 *             totalSize += Downloader.downloadFile(urls[i]);
 60 *             publishProgress((int) ((i / (float) count) * 100));
 61 *         }
 62 *     }
 63 *
 64 *     public void onProgressUpdate(Integer... progress) {
 65 *         setProgressPercent(progress[0]);
 66 *     }
 67 *
 68 *     public void onPostExecute(Long result) {
 69 *         showDialog("Downloaded " + result + " bytes");
 70 *     }
 71 * }
 72 * </pre>
 73 *
 74 * <p>Once created, a task is executed very simply:</p>
 75 * <pre>
 76 * new DownloadFilesTask().execute(new URL[] { ... });
 77 * </pre>
 78 *
 79 * <h2>User task's generic types</h2>
 80 * <p>The three types used by a user task are the following:</p>
 81 * <ol>
 82 *     <li><code>Params</code>, the type of the parameters sent to the task upon
 83 *     execution.</li>
 84 *     <li><code>Progress</code>, the type of the progress units published during
 85 *     the background computation.</li>
 86 *     <li><code>Result</code>, the type of the result of the background
 87 *     computation.</li>
 88 * </ol>
 89 * <p>Not all types are always used by a user task. To mark a type as unused,
 90 * simply use the type {@link Void}:</p>
 91 * <pre>
 92 * private class MyTask extends UserTask<Void, Void, Void) { ... }
 93 * </pre>
 94 *
 95 * <h2>The 4 steps</h2>
 96 * <p>When a user task is executed, the task goes through 4 steps:</p>
 97 * <ol>
 98 *     <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task
 99 *     is executed. This step is normally used to setup the task, for instance by
100 *     showing a progress bar in the user interface.</li>
101 *     <li>{@link #doInBackground(Object[])}, invoked on the background thread
102 *     immediately after {@link # onPreExecute ()} finishes executing. This step is used
103 *     to perform background computation that can take a long time. The parameters
104 *     of the user task are passed to this step. The result of the computation must
105 *     be returned by this step and will be passed back to the last step. This step
106 *     can also use {@link #publishProgress(Object[])} to publish one or more units
107 *     of progress. These values are published on the UI thread, in the
108 *     {@link #onProgressUpdate(Object[])} step.</li>
109 *     <li>{@link # onProgressUpdate (Object[])}, invoked on the UI thread after a
110 *     call to {@link #publishProgress(Object[])}. The timing of the execution is
111 *     undefined. This method is used to display any form of progress in the user
112 *     interface while the background computation is still executing. For instance,
113 *     it can be used to animate a progress bar or show logs in a text field.</li>
114 *     <li>{@link # onPostExecute (Object)}, invoked on the UI thread after the background
115 *     computation finishes. The result of the background computation is passed to
116 *     this step as a parameter.</li>
117 * </ol>
118 *
119 * <h2>Threading rules</h2>
120 * <p>There are a few threading rules that must be followed for this class to
121 * work properly:</p>
122 * <ul>
123 *     <li>The task instance must be created on the UI thread.</li>
124 *     <li>{@link #execute(Object[])} must be invoked on the UI thread.</li>
125 *     <li>Do not call {@link # onPreExecute ()}, {@link # onPostExecute (Object)},
126 *     {@link #doInBackground(Object[])}, {@link # onProgressUpdate (Object[])}
127 *     manually.</li>
128 *     <li>The task can be executed only once (an exception will be thrown if
129 *     a second execution is attempted.)</li>
130 * </ul>
131 */
132public abstract class UserTask<Params, Progress, Result> {
133    private static final String LOG_TAG = "UserTask";
134
135    private static final int CORE_POOL_SIZE = 1;
136    private static final int MAXIMUM_POOL_SIZE = 10;
137    private static final int KEEP_ALIVE = 10;
138
139    private static final BlockingQueue<Runnable> sWorkQueue =
140            new LinkedBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE);
141
142    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
143        private final AtomicInteger mCount = new AtomicInteger(1);
144
145        public Thread newThread(Runnable r) {
146            return new Thread(r, "UserTask #" + mCount.getAndIncrement());
147        }
148    };
149
150    private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
151            MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
152
153    private static final int MESSAGE_POST_RESULT = 0x1;
154    private static final int MESSAGE_POST_PROGRESS = 0x2;
155    private static final int MESSAGE_POST_CANCEL = 0x3;
156
157    private static final InternalHandler sHandler = new InternalHandler();
158
159    private final WorkerRunnable<Params, Result> mWorker;
160    private final FutureTask<Result> mFuture;
161
162    private volatile Status mStatus = Status.PENDING;
163
164    /**
165     * Indicates the current status of the task. Each status will be set only once
166     * during the lifetime of a task.
167     */
168    public enum Status {
169        /**
170         * Indicates that the task has not been executed yet.
171         */
172        PENDING,
173        /**
174         * Indicates that the task is running.
175         */
176        RUNNING,
177        /**
178         * Indicates that {@link UserTask#onPostExecute(Object)} has finished.
179         */
180        FINISHED,
181    }
182
183    /**
184     * Creates a new user task. This constructor must be invoked on the UI thread.
185     */
186    public UserTask() {
187        mWorker = new WorkerRunnable<Params, Result>() {
188            public Result call() throws Exception {
189                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
190                return doInBackground(mParams);
191            }
192        };
193
194        mFuture = new FutureTask<Result>(mWorker) {
195            @Override
196            protected void done() {
197                Message message;
198                Result result = null;
199
200                try {
201                    result = get();
202                } catch (InterruptedException e) {
203                    android.util.Log.w(LOG_TAG, e);
204                } catch (ExecutionException e) {
205                    throw new RuntimeException("An error occured while executing doInBackground()",
206                            e.getCause());
207                } catch (CancellationException e) {
208                    message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
209                            new UserTaskResult<Result>(UserTask.this, (Result[]) null));
210                    message.sendToTarget();
211                    return;
212                } catch (Throwable t) {
213                    throw new RuntimeException("An error occured while executing "
214                            + "doInBackground()", t);
215                }
216
217                message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
218                        new UserTaskResult<Result>(UserTask.this, result));
219                message.sendToTarget();
220            }
221        };
222    }
223
224    /**
225     * Returns the current status of this task.
226     *
227     * @return The current status.
228     */
229    public final Status getStatus() {
230        return mStatus;
231    }
232
233    /**
234     * Override this method to perform a computation on a background thread. The
235     * specified parameters are the parameters passed to {@link #execute(Object[])}
236     * by the caller of this task.
237     *
238     * This method can call {@link #publishProgress(Object[])} to publish updates
239     * on the UI thread.
240     *
241     * @param params The parameters of the task.
242     *
243     * @return A result, defined by the subclass of this task.
244     *
245     * @see #onPreExecute()
246     * @see #onPostExecute(Object)
247     * @see #publishProgress(Object[])
248     */
249    public abstract Result doInBackground(Params... params);
250
251    /**
252     * Runs on the UI thread before {@link #doInBackground(Object[])}.
253     *
254     * @see #onPostExecute(Object)
255     * @see #doInBackground(Object[])
256     */
257    public void onPreExecute() {
258    }
259
260    /**
261     * Runs on the UI thread after {@link #doInBackground(Object[])}. The
262     * specified result is the value returned by {@link #doInBackground(Object[])}
263     * or null if the task was cancelled or an exception occured.
264     *
265     * @param result The result of the operation computed by {@link #doInBackground(Object[])}.
266     *
267     * @see #onPreExecute()
268     * @see #doInBackground(Object[])
269     */
270    @SuppressWarnings({"UnusedDeclaration"})
271    public void onPostExecute(Result result) {
272    }
273
274    /**
275     * Runs on the UI thread after {@link #publishProgress(Object[])} is invoked.
276     * The specified values are the values passed to {@link #publishProgress(Object[])}.
277     *
278     * @param values The values indicating progress.
279     *
280     * @see #publishProgress(Object[])
281     * @see #doInBackground(Object[])
282     */
283    @SuppressWarnings({"UnusedDeclaration"})
284    public void onProgressUpdate(Progress... values) {
285    }
286
287    /**
288     * Runs on the UI thread after {@link #cancel(boolean)} is invoked.
289     *
290     * @see #cancel(boolean)
291     * @see #isCancelled()
292     */
293    public void onCancelled() {
294    }
295
296    /**
297     * Returns <tt>true</tt> if this task was cancelled before it completed
298     * normally.
299     *
300     * @return <tt>true</tt> if task was cancelled before it completed
301     *
302     * @see #cancel(boolean)
303     */
304    public final boolean isCancelled() {
305        return mFuture.isCancelled();
306    }
307
308    /**
309     * Attempts to cancel execution of this task.  This attempt will
310     * fail if the task has already completed, already been cancelled,
311     * or could not be cancelled for some other reason. If successful,
312     * and this task has not started when <tt>cancel</tt> is called,
313     * this task should never run.  If the task has already started,
314     * then the <tt>mayInterruptIfRunning</tt> parameter determines
315     * whether the thread executing this task should be interrupted in
316     * an attempt to stop the task.
317     *
318     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
319     *        task should be interrupted; otherwise, in-progress tasks are allowed
320     *        to complete.
321     *
322     * @return <tt>false</tt> if the task could not be cancelled,
323     *         typically because it has already completed normally;
324     *         <tt>true</tt> otherwise
325     *
326     * @see #isCancelled()
327     * @see #onCancelled()
328     */
329    public final boolean cancel(boolean mayInterruptIfRunning) {
330        return mFuture.cancel(mayInterruptIfRunning);
331    }
332
333    /**
334     * Waits if necessary for the computation to complete, and then
335     * retrieves its result.
336     *
337     * @return The computed result.
338     *
339     * @throws CancellationException If the computation was cancelled.
340     * @throws ExecutionException If the computation threw an exception.
341     * @throws InterruptedException If the current thread was interrupted
342     *         while waiting.
343     */
344    public final Result get() throws InterruptedException, ExecutionException {
345        return mFuture.get();
346    }
347
348    /**
349     * Waits if necessary for at most the given time for the computation
350     * to complete, and then retrieves its result.
351     *
352     * @param timeout Time to wait before cancelling the operation.
353     * @param unit The time unit for the timeout.
354     *
355     * @return The computed result.
356     *
357     * @throws CancellationException If the computation was cancelled.
358     * @throws ExecutionException If the computation threw an exception.
359     * @throws InterruptedException If the current thread was interrupted
360     *         while waiting.
361     * @throws TimeoutException If the wait timed out.
362     */
363    public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
364            ExecutionException, TimeoutException {
365        return mFuture.get(timeout, unit);
366    }
367
368    /**
369     * Executes the task with the specified parameters. The task returns
370     * itself (this) so that the caller can keep a reference to it.
371     *
372     * This method must be invoked on the UI thread.
373     *
374     * @param params The parameters of the task.
375     *
376     * @return This instance of UserTask.
377     *
378     * @throws IllegalStateException If {@link #getStatus()} returns either
379     *         {@link UserTask.Status#RUNNING} or {@link UserTask.Status#FINISHED}.
380     */
381    public final UserTask<Params, Progress, Result> execute(Params... params) {
382        if (mStatus != Status.PENDING) {
383            switch (mStatus) {
384                case RUNNING:
385                    throw new IllegalStateException("Cannot execute task:"
386                            + " the task is already running.");
387                case FINISHED:
388                    throw new IllegalStateException("Cannot execute task:"
389                            + " the task has already been executed "
390                            + "(a task can be executed only once)");
391            }
392        }
393
394        mStatus = Status.RUNNING;
395
396        onPreExecute();
397
398        mWorker.mParams = params;
399        sExecutor.execute(mFuture);
400
401        return this;
402    }
403
404    /**
405     * This method can be invoked from {@link #doInBackground(Object[])} to
406     * publish updates on the UI thread while the background computation is
407     * still running. Each call to this method will trigger the execution of
408     * {@link #onProgressUpdate(Object[])} on the UI thread.
409     *
410     * @param values The progress values to update the UI with.
411     *
412     * @see # onProgressUpdate (Object[])
413     * @see #doInBackground(Object[])
414     */
415    protected final void publishProgress(Progress... values) {
416        sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
417                new UserTaskResult<Progress>(this, values)).sendToTarget();
418    }
419
420    private void finish(Result result) {
421        onPostExecute(result);
422        mStatus = Status.FINISHED;
423    }
424
425    private static class InternalHandler extends Handler {
426        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
427        @Override
428        public void handleMessage(Message msg) {
429            UserTaskResult result = (UserTaskResult) msg.obj;
430            switch (msg.what) {
431                case MESSAGE_POST_RESULT:
432                    // There is only one result
433                    result.mTask.finish(result.mData[0]);
434                    break;
435                case MESSAGE_POST_PROGRESS:
436                    result.mTask.onProgressUpdate(result.mData);
437                    break;
438                case MESSAGE_POST_CANCEL:
439                    result.mTask.onCancelled();
440                    break;
441            }
442        }
443    }
444
445    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
446        Params[] mParams;
447    }
448
449    @SuppressWarnings({"RawUseOfParameterizedType"})
450    private static class UserTaskResult<Data> {
451        final UserTask mTask;
452        final Data[] mData;
453
454        UserTaskResult(UserTask task, Data... data) {
455            mTask = task;
456            mData = data;
457        }
458    }
459}