|
| 1 | +package www.codingwith.us.task; |
| 2 | + |
| 3 | +import java.util.concurrent.Callable; |
| 4 | +import java.util.concurrent.CancellationException; |
| 5 | +import java.util.concurrent.ExecutionException; |
| 6 | +import java.util.concurrent.ExecutorService; |
| 7 | +import java.util.concurrent.Executors; |
| 8 | +import java.util.concurrent.FutureTask; |
| 9 | +import java.util.concurrent.ThreadFactory; |
| 10 | +import java.util.concurrent.TimeUnit; |
| 11 | +import java.util.concurrent.TimeoutException; |
| 12 | +import java.util.concurrent.atomic.AtomicInteger; |
| 13 | + |
| 14 | +import android.os.Handler; |
| 15 | +import android.os.Message; |
| 16 | +import android.os.Process; |
| 17 | + |
| 18 | +public abstract class BaseAsyncTask<Params, Progress, Result> { |
| 19 | + private static final String LOG_TAG = "FifoAsyncTask"; |
| 20 | + private static final int NUMBER_THREAD = 10; |
| 21 | + |
| 22 | + // private static final int CORE_POOL_SIZE = 5; |
| 23 | + // private static final int MAXIMUM_POOL_SIZE = 5; |
| 24 | + // private static final int KEEP_ALIVE = 1; |
| 25 | + |
| 26 | + // private static final BlockingQueue<Runnable> sWorkQueue = |
| 27 | + // new LinkedBlockingQueue<Runnable>(); |
| 28 | + // |
| 29 | + private static final ThreadFactory sThreadFactory = new ThreadFactory() { |
| 30 | + private final AtomicInteger mCount = new AtomicInteger(1); |
| 31 | + |
| 32 | + public Thread newThread(Runnable r) { |
| 33 | + return new Thread(r, "PreReadTask #" + mCount.getAndIncrement()); |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + private static final ExecutorService sExecutor = Executors |
| 38 | + .newFixedThreadPool(NUMBER_THREAD, sThreadFactory);// ֻ��һ�������̵߳��̳߳� |
| 39 | + |
| 40 | + private static final int MESSAGE_POST_RESULT = 0x1; |
| 41 | + private static final int MESSAGE_POST_PROGRESS = 0x2; |
| 42 | + private static final int MESSAGE_POST_CANCEL = 0x3; |
| 43 | + |
| 44 | + private static final InternalHandler sHandler = new InternalHandler(); |
| 45 | + |
| 46 | + private final WorkerRunnable<Params, Result> mWorker; |
| 47 | + private final FutureTask<Result> mFuture; |
| 48 | + |
| 49 | + private volatile Status mStatus = Status.PENDING; |
| 50 | + |
| 51 | + /** |
| 52 | + * Indicates the current status of the task. Each status will be set only |
| 53 | + * once during the lifetime of a task. |
| 54 | + */ |
| 55 | + public enum Status { |
| 56 | + /** |
| 57 | + * Indicates that the task has not been executed yet. |
| 58 | + */ |
| 59 | + PENDING, |
| 60 | + /** |
| 61 | + * Indicates that the task is running. |
| 62 | + */ |
| 63 | + RUNNING, |
| 64 | + /** |
| 65 | + * Indicates that {@link FifoAsyncTask#onPostExecute} has finished. |
| 66 | + */ |
| 67 | + FINISHED, |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Creates a new asynchronous task. This constructor must be invoked on the |
| 72 | + * UI thread. |
| 73 | + */ |
| 74 | + public BaseAsyncTask() { |
| 75 | + mWorker = new WorkerRunnable<Params, Result>() { |
| 76 | + public Result call() throws Exception { |
| 77 | + Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); |
| 78 | + return doInBackground(mParams); |
| 79 | + } |
| 80 | + }; |
| 81 | + |
| 82 | + mFuture = new FutureTask<Result>(mWorker) { |
| 83 | + @Override |
| 84 | + protected void done() { |
| 85 | + Message message; |
| 86 | + Result result = null; |
| 87 | + |
| 88 | + try { |
| 89 | + result = get(); |
| 90 | + } catch (InterruptedException e) { |
| 91 | + android.util.Log.w(LOG_TAG, e); |
| 92 | + } catch (ExecutionException e) { |
| 93 | + throw new RuntimeException( |
| 94 | + "An error occured while executing doInBackground()", |
| 95 | + e.getCause()); |
| 96 | + } catch (CancellationException e) { |
| 97 | + message = sHandler.obtainMessage(MESSAGE_POST_CANCEL, |
| 98 | + new PreReadTaskResult<Result>(BaseAsyncTask.this, |
| 99 | + (Result[]) null)); |
| 100 | + message.sendToTarget(); |
| 101 | + return; |
| 102 | + } catch (Throwable t) { |
| 103 | + throw new RuntimeException( |
| 104 | + "An error occured while executing " |
| 105 | + + "doInBackground()", t); |
| 106 | + } |
| 107 | + |
| 108 | + message = sHandler |
| 109 | + .obtainMessage(MESSAGE_POST_RESULT, |
| 110 | + new PreReadTaskResult<Result>(BaseAsyncTask.this, |
| 111 | + result)); |
| 112 | + message.sendToTarget(); |
| 113 | + } |
| 114 | + }; |
| 115 | + } |
| 116 | + |
| 117 | + /** |
| 118 | + * Returns the current status of this task. |
| 119 | + * |
| 120 | + * @return The current status. |
| 121 | + */ |
| 122 | + public final Status getStatus() { |
| 123 | + return mStatus; |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Override this method to perform a computation on a background thread. The |
| 128 | + * specified parameters are the parameters passed to {@link #execute} by the |
| 129 | + * caller of this task. |
| 130 | + * |
| 131 | + * This method can call {@link #publishProgress} to publish updates on the |
| 132 | + * UI thread. |
| 133 | + * |
| 134 | + * @param params |
| 135 | + * The parameters of the task. |
| 136 | + * |
| 137 | + * @return A result, defined by the subclass of this task. |
| 138 | + * |
| 139 | + * @see #onPreExecute() |
| 140 | + * @see #onPostExecute |
| 141 | + * @see #publishProgress |
| 142 | + */ |
| 143 | + protected abstract Result doInBackground(Params... params); |
| 144 | + |
| 145 | + /** |
| 146 | + * Runs on the UI thread before {@link #doInBackground}. |
| 147 | + * |
| 148 | + * @see #onPostExecute |
| 149 | + * @see #doInBackground |
| 150 | + */ |
| 151 | + protected void onPreExecute() { |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Runs on the UI thread after {@link #doInBackground}. The specified result |
| 156 | + * is the value returned by {@link #doInBackground} or null if the task was |
| 157 | + * cancelled or an exception occured. |
| 158 | + * |
| 159 | + * @param result |
| 160 | + * The result of the operation computed by |
| 161 | + * {@link #doInBackground}. |
| 162 | + * |
| 163 | + * @see #onPreExecute |
| 164 | + * @see #doInBackground |
| 165 | + */ |
| 166 | + @SuppressWarnings({ "UnusedDeclaration" }) |
| 167 | + protected void onPostExecute(Result result) { |
| 168 | + } |
| 169 | + |
| 170 | + /** |
| 171 | + * Runs on the UI thread after {@link #publishProgress} is invoked. The |
| 172 | + * specified values are the values passed to {@link #publishProgress}. |
| 173 | + * |
| 174 | + * @param values |
| 175 | + * The values indicating progress. |
| 176 | + * |
| 177 | + * @see #publishProgress |
| 178 | + * @see #doInBackground |
| 179 | + */ |
| 180 | + @SuppressWarnings({ "UnusedDeclaration" }) |
| 181 | + protected void onProgressUpdate(Progress... values) { |
| 182 | + } |
| 183 | + |
| 184 | + /** |
| 185 | + * Runs on the UI thread after {@link #cancel(boolean)} is invoked. |
| 186 | + * |
| 187 | + * @see #cancel(boolean) |
| 188 | + * @see #isCancelled() |
| 189 | + */ |
| 190 | + protected void onCancelled() { |
| 191 | + } |
| 192 | + |
| 193 | + /** |
| 194 | + * Returns <tt>true</tt> if this task was cancelled before it completed |
| 195 | + * normally. |
| 196 | + * |
| 197 | + * @return <tt>true</tt> if task was cancelled before it completed |
| 198 | + * |
| 199 | + * @see #cancel(boolean) |
| 200 | + */ |
| 201 | + public final boolean isCancelled() { |
| 202 | + return mFuture.isCancelled(); |
| 203 | + } |
| 204 | + |
| 205 | + /** |
| 206 | + * Attempts to cancel execution of this task. This attempt will fail if the |
| 207 | + * task has already completed, already been cancelled, or could not be |
| 208 | + * cancelled for some other reason. If successful, and this task has not |
| 209 | + * started when <tt>cancel</tt> is called, this task should never run. If |
| 210 | + * the task has already started, then the <tt>mayInterruptIfRunning</tt> |
| 211 | + * parameter determines whether the thread executing this task should be |
| 212 | + * interrupted in an attempt to stop the task. |
| 213 | + * |
| 214 | + * @param mayInterruptIfRunning |
| 215 | + * <tt>true</tt> if the thread executing this task should be |
| 216 | + * interrupted; otherwise, in-progress tasks are allowed to |
| 217 | + * complete. |
| 218 | + * |
| 219 | + * @return <tt>false</tt> if the task could not be cancelled, typically |
| 220 | + * because it has already completed normally; <tt>true</tt> |
| 221 | + * otherwise |
| 222 | + * |
| 223 | + * @see #isCancelled() |
| 224 | + * @see #onCancelled() |
| 225 | + */ |
| 226 | + public final boolean cancel(boolean mayInterruptIfRunning) { |
| 227 | + return mFuture.cancel(mayInterruptIfRunning); |
| 228 | + } |
| 229 | + |
| 230 | + /** |
| 231 | + * Waits if necessary for the computation to complete, and then retrieves |
| 232 | + * its result. |
| 233 | + * |
| 234 | + * @return The computed result. |
| 235 | + * |
| 236 | + * @throws CancellationException |
| 237 | + * If the computation was cancelled. |
| 238 | + * @throws ExecutionException |
| 239 | + * If the computation threw an exception. |
| 240 | + * @throws InterruptedException |
| 241 | + * If the current thread was interrupted while waiting. |
| 242 | + */ |
| 243 | + public final Result get() throws InterruptedException, ExecutionException { |
| 244 | + return mFuture.get(); |
| 245 | + } |
| 246 | + |
| 247 | + /** |
| 248 | + * Waits if necessary for at most the given time for the computation to |
| 249 | + * complete, and then retrieves its result. |
| 250 | + * |
| 251 | + * @param timeout |
| 252 | + * Time to wait before cancelling the operation. |
| 253 | + * @param unit |
| 254 | + * The time unit for the timeout. |
| 255 | + * |
| 256 | + * @return The computed result. |
| 257 | + * |
| 258 | + * @throws CancellationException |
| 259 | + * If the computation was cancelled. |
| 260 | + * @throws ExecutionException |
| 261 | + * If the computation threw an exception. |
| 262 | + * @throws InterruptedException |
| 263 | + * If the current thread was interrupted while waiting. |
| 264 | + * @throws TimeoutException |
| 265 | + * If the wait timed out. |
| 266 | + */ |
| 267 | + public final Result get(long timeout, TimeUnit unit) |
| 268 | + throws InterruptedException, ExecutionException, TimeoutException { |
| 269 | + return mFuture.get(timeout, unit); |
| 270 | + } |
| 271 | + |
| 272 | + /** |
| 273 | + * Executes the task with the specified parameters. The task returns itself |
| 274 | + * (this) so that the caller can keep a reference to it. |
| 275 | + * |
| 276 | + * This method must be invoked on the UI thread. |
| 277 | + * |
| 278 | + * @param params |
| 279 | + * The parameters of the task. |
| 280 | + * |
| 281 | + * @return This instance of AsyncTask. |
| 282 | + * |
| 283 | + * @throws IllegalStateException |
| 284 | + * If {@link #getStatus()} returns either |
| 285 | + * {@link FifoAsyncTask.Status#RUNNING} or |
| 286 | + * {@link FifoAsyncTask.Status#FINISHED}. |
| 287 | + */ |
| 288 | + public final BaseAsyncTask<Params, Progress, Result> execute(Params... params) { |
| 289 | + if (mStatus != Status.PENDING) { |
| 290 | + switch (mStatus) { |
| 291 | + case RUNNING: |
| 292 | + throw new IllegalStateException("Cannot execute task:" |
| 293 | + + " the task is already running."); |
| 294 | + case FINISHED: |
| 295 | + throw new IllegalStateException("Cannot execute task:" |
| 296 | + + " the task has already been executed " |
| 297 | + + "(a task can be executed only once)"); |
| 298 | + } |
| 299 | + } |
| 300 | + |
| 301 | + mStatus = Status.RUNNING; |
| 302 | + |
| 303 | + onPreExecute(); |
| 304 | + |
| 305 | + mWorker.mParams = params; |
| 306 | + sExecutor.execute(mFuture); |
| 307 | + |
| 308 | + return this; |
| 309 | + } |
| 310 | + |
| 311 | + /** |
| 312 | + * This method can be invoked from {@link #doInBackground} to publish |
| 313 | + * updates on the UI thread while the background computation is still |
| 314 | + * running. Each call to this method will trigger the execution of |
| 315 | + * {@link #onProgressUpdate} on the UI thread. |
| 316 | + * |
| 317 | + * @param values |
| 318 | + * The progress values to update the UI with. |
| 319 | + * |
| 320 | + * @see #onProgressUpdate |
| 321 | + * @see #doInBackground |
| 322 | + */ |
| 323 | + protected final void publishProgress(Progress... values) { |
| 324 | + sHandler.obtainMessage(MESSAGE_POST_PROGRESS, |
| 325 | + new PreReadTaskResult<Progress>(this, values)).sendToTarget(); |
| 326 | + } |
| 327 | + |
| 328 | + private void finish(Result result) { |
| 329 | + if (isCancelled()) |
| 330 | + result = null; |
| 331 | + onPostExecute(result); |
| 332 | + mStatus = Status.FINISHED; |
| 333 | + } |
| 334 | + |
| 335 | + private static class InternalHandler extends Handler { |
| 336 | + @SuppressWarnings({ "unchecked", "RawUseOfParameterizedType" }) |
| 337 | + @Override |
| 338 | + public void handleMessage(Message msg) { |
| 339 | + PreReadTaskResult result = (PreReadTaskResult) msg.obj; |
| 340 | + switch (msg.what) { |
| 341 | + case MESSAGE_POST_RESULT: |
| 342 | + // There is only one result |
| 343 | + result.mTask.finish(result.mData[0]); |
| 344 | + break; |
| 345 | + case MESSAGE_POST_PROGRESS: |
| 346 | + result.mTask.onProgressUpdate(result.mData); |
| 347 | + break; |
| 348 | + case MESSAGE_POST_CANCEL: |
| 349 | + result.mTask.onCancelled(); |
| 350 | + break; |
| 351 | + } |
| 352 | + } |
| 353 | + } |
| 354 | + |
| 355 | + private static abstract class WorkerRunnable<Params, Result> implements |
| 356 | + Callable<Result> { |
| 357 | + Params[] mParams; |
| 358 | + } |
| 359 | + |
| 360 | + @SuppressWarnings({ "RawUseOfParameterizedType" }) |
| 361 | + private static class PreReadTaskResult<Data> { |
| 362 | + final BaseAsyncTask mTask; |
| 363 | + final Data[] mData; |
| 364 | + |
| 365 | + PreReadTaskResult(BaseAsyncTask task, Data... data) { |
| 366 | + mTask = task; |
| 367 | + mData = data; |
| 368 | + } |
| 369 | + } |
| 370 | +} |
0 commit comments