Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
7859 views
1
/*
2
* Copyright (C) 2008 The Android Open Source Project
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
package com.artifex.mupdfdemo;
18
19
import java.util.concurrent.BlockingQueue;
20
import java.util.concurrent.Callable;
21
import java.util.concurrent.CancellationException;
22
import java.util.concurrent.ExecutionException;
23
import java.util.concurrent.Executor;
24
import java.util.concurrent.FutureTask;
25
import java.util.concurrent.LinkedBlockingQueue;
26
import java.util.concurrent.ThreadFactory;
27
import java.util.concurrent.ThreadPoolExecutor;
28
import java.util.concurrent.TimeUnit;
29
import java.util.concurrent.TimeoutException;
30
import java.util.concurrent.atomic.AtomicBoolean;
31
import java.util.concurrent.atomic.AtomicInteger;
32
33
import android.os.Process;
34
import android.os.Handler;
35
import android.os.Message;
36
37
/**
38
* <p>AsyncTask enables proper and easy use of the UI thread. This class allows to
39
* perform background operations and publish results on the UI thread without
40
* having to manipulate threads and/or handlers.</p>
41
*
42
* <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler}
43
* and does not constitute a generic threading framework. AsyncTasks should ideally be
44
* used for short operations (a few seconds at the most.) If you need to keep threads
45
* running for long periods of time, it is highly recommended you use the various APIs
46
* provided by the <code>java.util.concurrent</code> pacakge such as {@link Executor},
47
* {@link ThreadPoolExecutor} and {@link FutureTask}.</p>
48
*
49
* <p>An asynchronous task is defined by a computation that runs on a background thread and
50
* whose result is published on the UI thread. An asynchronous task is defined by 3 generic
51
* types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
52
* and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>,
53
* <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p>
54
*
55
* <div class="special reference">
56
* <h3>Developer Guides</h3>
57
* <p>For more information about using tasks and threads, read the
58
* <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
59
* Threads</a> developer guide.</p>
60
* </div>
61
*
62
* <h2>Usage</h2>
63
* <p>AsyncTask must be subclassed to be used. The subclass will override at least
64
* one method ({@link #doInBackground}), and most often will override a
65
* second one ({@link #onPostExecute}.)</p>
66
*
67
* <p>Here is an example of subclassing:</p>
68
* <pre class="prettyprint">
69
* private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; {
70
* protected Long doInBackground(URL... urls) {
71
* int count = urls.length;
72
* long totalSize = 0;
73
* for (int i = 0; i < count; i++) {
74
* totalSize += Downloader.downloadFile(urls[i]);
75
* publishProgress((int) ((i / (float) count) * 100));
76
* // Escape early if cancel() is called
77
* if (isCancelled()) break;
78
* }
79
* return totalSize;
80
* }
81
*
82
* protected void onProgressUpdate(Integer... progress) {
83
* setProgressPercent(progress[0]);
84
* }
85
*
86
* protected void onPostExecute(Long result) {
87
* showDialog("Downloaded " + result + " bytes");
88
* }
89
* }
90
* </pre>
91
*
92
* <p>Once created, a task is executed very simply:</p>
93
* <pre class="prettyprint">
94
* new DownloadFilesTask().execute(url1, url2, url3);
95
* </pre>
96
*
97
* <h2>AsyncTask's generic types</h2>
98
* <p>The three types used by an asynchronous task are the following:</p>
99
* <ol>
100
* <li><code>Params</code>, the type of the parameters sent to the task upon
101
* execution.</li>
102
* <li><code>Progress</code>, the type of the progress units published during
103
* the background computation.</li>
104
* <li><code>Result</code>, the type of the result of the background
105
* computation.</li>
106
* </ol>
107
* <p>Not all types are always used by an asynchronous task. To mark a type as unused,
108
* simply use the type {@link Void}:</p>
109
* <pre>
110
* private class MyTask extends AsyncTask&lt;Void, Void, Void&gt; { ... }
111
* </pre>
112
*
113
* <h2>The 4 steps</h2>
114
* <p>When an asynchronous task is executed, the task goes through 4 steps:</p>
115
* <ol>
116
* <li>{@link #onPreExecute()}, invoked on the UI thread before the task
117
* is executed. This step is normally used to setup the task, for instance by
118
* showing a progress bar in the user interface.</li>
119
* <li>{@link #doInBackground}, invoked on the background thread
120
* immediately after {@link #onPreExecute()} finishes executing. This step is used
121
* to perform background computation that can take a long time. The parameters
122
* of the asynchronous task are passed to this step. The result of the computation must
123
* be returned by this step and will be passed back to the last step. This step
124
* can also use {@link #publishProgress} to publish one or more units
125
* of progress. These values are published on the UI thread, in the
126
* {@link #onProgressUpdate} step.</li>
127
* <li>{@link #onProgressUpdate}, invoked on the UI thread after a
128
* call to {@link #publishProgress}. The timing of the execution is
129
* undefined. This method is used to display any form of progress in the user
130
* interface while the background computation is still executing. For instance,
131
* it can be used to animate a progress bar or show logs in a text field.</li>
132
* <li>{@link #onPostExecute}, invoked on the UI thread after the background
133
* computation finishes. The result of the background computation is passed to
134
* this step as a parameter.</li>
135
* </ol>
136
*
137
* <h2>Cancelling a task</h2>
138
* <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking
139
* this method will cause subsequent calls to {@link #isCancelled()} to return true.
140
* After invoking this method, {@link #onCancelled(Object)}, instead of
141
* {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])}
142
* returns. To ensure that a task is cancelled as quickly as possible, you should always
143
* check the return value of {@link #isCancelled()} periodically from
144
* {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p>
145
*
146
* <h2>Threading rules</h2>
147
* <p>There are a few threading rules that must be followed for this class to
148
* work properly:</p>
149
* <ul>
150
* <li>The AsyncTask class must be loaded on the UI thread. This is done
151
* automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li>
152
* <li>The task instance must be created on the UI thread.</li>
153
* <li>{@link #execute} must be invoked on the UI thread.</li>
154
* <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute},
155
* {@link #doInBackground}, {@link #onProgressUpdate} manually.</li>
156
* <li>The task can be executed only once (an exception will be thrown if
157
* a second execution is attempted.)</li>
158
* </ul>
159
*
160
* <h2>Memory observability</h2>
161
* <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following
162
* operations are safe without explicit synchronizations.</p>
163
* <ul>
164
* <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them
165
* in {@link #doInBackground}.
166
* <li>Set member fields in {@link #doInBackground}, and refer to them in
167
* {@link #onProgressUpdate} and {@link #onPostExecute}.
168
* </ul>
169
*
170
* <h2>Order of execution</h2>
171
* <p>When first introduced, AsyncTasks were executed serially on a single background
172
* thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
173
* to a pool of threads allowing multiple tasks to operate in parallel. Starting with
174
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single
175
* thread to avoid common application errors caused by parallel execution.</p>
176
* <p>If you truly want parallel execution, you can invoke
177
* {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with
178
* {@link #THREAD_POOL_EXECUTOR}.</p>
179
*/
180
public abstract class AsyncTask<Params, Progress, Result> {
181
private static final String LOG_TAG = "AsyncTask";
182
183
private static final int CORE_POOL_SIZE = 5;
184
private static final int MAXIMUM_POOL_SIZE = 128;
185
private static final int KEEP_ALIVE = 1;
186
187
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
188
private final AtomicInteger mCount = new AtomicInteger(1);
189
190
public Thread newThread(Runnable r) {
191
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
192
}
193
};
194
195
private static final BlockingQueue<Runnable> sPoolWorkQueue =
196
new LinkedBlockingQueue<Runnable>(10);
197
198
/**
199
* An {@link Executor} that can be used to execute tasks in parallel.
200
*/
201
public static final Executor THREAD_POOL_EXECUTOR
202
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
203
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
204
205
/**
206
* An {@link Executor} that executes tasks one at a time in serial
207
* order. This serialization is global to a particular process.
208
*/
209
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
210
211
private static final int MESSAGE_POST_RESULT = 0x1;
212
private static final int MESSAGE_POST_PROGRESS = 0x2;
213
214
private static final InternalHandler sHandler = new InternalHandler();
215
216
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
217
private final WorkerRunnable<Params, Result> mWorker;
218
private final FutureTask<Result> mFuture;
219
220
private volatile Status mStatus = Status.PENDING;
221
222
private final AtomicBoolean mCancelled = new AtomicBoolean();
223
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
224
225
private static class SerialExecutor implements Executor {
226
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
227
Runnable mActive;
228
229
public synchronized void execute(final Runnable r) {
230
mTasks.offer(new Runnable() {
231
public void run() {
232
try {
233
r.run();
234
} finally {
235
scheduleNext();
236
}
237
}
238
});
239
if (mActive == null) {
240
scheduleNext();
241
}
242
}
243
244
protected synchronized void scheduleNext() {
245
if ((mActive = mTasks.poll()) != null) {
246
THREAD_POOL_EXECUTOR.execute(mActive);
247
}
248
}
249
}
250
251
/**
252
* Indicates the current status of the task. Each status will be set only once
253
* during the lifetime of a task.
254
*/
255
public enum Status {
256
/**
257
* Indicates that the task has not been executed yet.
258
*/
259
PENDING,
260
/**
261
* Indicates that the task is running.
262
*/
263
RUNNING,
264
/**
265
* Indicates that {@link AsyncTask#onPostExecute} has finished.
266
*/
267
FINISHED,
268
}
269
270
/** @hide Used to force static handler to be created. */
271
public static void init() {
272
sHandler.getLooper();
273
}
274
275
/** @hide */
276
public static void setDefaultExecutor(Executor exec) {
277
sDefaultExecutor = exec;
278
}
279
280
/**
281
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
282
*/
283
public AsyncTask() {
284
mWorker = new WorkerRunnable<Params, Result>() {
285
public Result call() throws Exception {
286
mTaskInvoked.set(true);
287
288
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
289
//noinspection unchecked
290
return postResult(doInBackground(mParams));
291
}
292
};
293
294
mFuture = new FutureTask<Result>(mWorker) {
295
@Override
296
protected void done() {
297
try {
298
postResultIfNotInvoked(get());
299
} catch (InterruptedException e) {
300
android.util.Log.w(LOG_TAG, e);
301
} catch (ExecutionException e) {
302
throw new RuntimeException("An error occured while executing doInBackground()",
303
e.getCause());
304
} catch (CancellationException e) {
305
postResultIfNotInvoked(null);
306
}
307
}
308
};
309
}
310
311
private void postResultIfNotInvoked(Result result) {
312
final boolean wasTaskInvoked = mTaskInvoked.get();
313
if (!wasTaskInvoked) {
314
postResult(result);
315
}
316
}
317
318
private Result postResult(Result result) {
319
@SuppressWarnings("unchecked")
320
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
321
new AsyncTaskResult<Result>(this, result));
322
message.sendToTarget();
323
return result;
324
}
325
326
/**
327
* Returns the current status of this task.
328
*
329
* @return The current status.
330
*/
331
public final Status getStatus() {
332
return mStatus;
333
}
334
335
/**
336
* Override this method to perform a computation on a background thread. The
337
* specified parameters are the parameters passed to {@link #execute}
338
* by the caller of this task.
339
*
340
* This method can call {@link #publishProgress} to publish updates
341
* on the UI thread.
342
*
343
* @param params The parameters of the task.
344
*
345
* @return A result, defined by the subclass of this task.
346
*
347
* @see #onPreExecute()
348
* @see #onPostExecute
349
* @see #publishProgress
350
*/
351
protected abstract Result doInBackground(Params... params);
352
353
/**
354
* Runs on the UI thread before {@link #doInBackground}.
355
*
356
* @see #onPostExecute
357
* @see #doInBackground
358
*/
359
protected void onPreExecute() {
360
}
361
362
/**
363
* <p>Runs on the UI thread after {@link #doInBackground}. The
364
* specified result is the value returned by {@link #doInBackground}.</p>
365
*
366
* <p>This method won't be invoked if the task was cancelled.</p>
367
*
368
* @param result The result of the operation computed by {@link #doInBackground}.
369
*
370
* @see #onPreExecute
371
* @see #doInBackground
372
* @see #onCancelled(Object)
373
*/
374
@SuppressWarnings({"UnusedDeclaration"})
375
protected void onPostExecute(Result result) {
376
}
377
378
/**
379
* Runs on the UI thread after {@link #publishProgress} is invoked.
380
* The specified values are the values passed to {@link #publishProgress}.
381
*
382
* @param values The values indicating progress.
383
*
384
* @see #publishProgress
385
* @see #doInBackground
386
*/
387
@SuppressWarnings({"UnusedDeclaration"})
388
protected void onProgressUpdate(Progress... values) {
389
}
390
391
/**
392
* <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
393
* {@link #doInBackground(Object[])} has finished.</p>
394
*
395
* <p>The default implementation simply invokes {@link #onCancelled()} and
396
* ignores the result. If you write your own implementation, do not call
397
* <code>super.onCancelled(result)</code>.</p>
398
*
399
* @param result The result, if any, computed in
400
* {@link #doInBackground(Object[])}, can be null
401
*
402
* @see #cancel(boolean)
403
* @see #isCancelled()
404
*/
405
@SuppressWarnings({"UnusedParameters"})
406
protected void onCancelled(Result result) {
407
onCancelled();
408
}
409
410
/**
411
* <p>Applications should preferably override {@link #onCancelled(Object)}.
412
* This method is invoked by the default implementation of
413
* {@link #onCancelled(Object)}.</p>
414
*
415
* <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
416
* {@link #doInBackground(Object[])} has finished.</p>
417
*
418
* @see #onCancelled(Object)
419
* @see #cancel(boolean)
420
* @see #isCancelled()
421
*/
422
protected void onCancelled() {
423
}
424
425
/**
426
* Returns <tt>true</tt> if this task was cancelled before it completed
427
* normally. If you are calling {@link #cancel(boolean)} on the task,
428
* the value returned by this method should be checked periodically from
429
* {@link #doInBackground(Object[])} to end the task as soon as possible.
430
*
431
* @return <tt>true</tt> if task was cancelled before it completed
432
*
433
* @see #cancel(boolean)
434
*/
435
public final boolean isCancelled() {
436
return mCancelled.get();
437
}
438
439
/**
440
* <p>Attempts to cancel execution of this task. This attempt will
441
* fail if the task has already completed, already been cancelled,
442
* or could not be cancelled for some other reason. If successful,
443
* and this task has not started when <tt>cancel</tt> is called,
444
* this task should never run. If the task has already started,
445
* then the <tt>mayInterruptIfRunning</tt> parameter determines
446
* whether the thread executing this task should be interrupted in
447
* an attempt to stop the task.</p>
448
*
449
* <p>Calling this method will result in {@link #onCancelled(Object)} being
450
* invoked on the UI thread after {@link #doInBackground(Object[])}
451
* returns. Calling this method guarantees that {@link #onPostExecute(Object)}
452
* is never invoked. After invoking this method, you should check the
453
* value returned by {@link #isCancelled()} periodically from
454
* {@link #doInBackground(Object[])} to finish the task as early as
455
* possible.</p>
456
*
457
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
458
* task should be interrupted; otherwise, in-progress tasks are allowed
459
* to complete.
460
*
461
* @return <tt>false</tt> if the task could not be cancelled,
462
* typically because it has already completed normally;
463
* <tt>true</tt> otherwise
464
*
465
* @see #isCancelled()
466
* @see #onCancelled(Object)
467
*/
468
public final boolean cancel(boolean mayInterruptIfRunning) {
469
mCancelled.set(true);
470
return mFuture.cancel(mayInterruptIfRunning);
471
}
472
473
/**
474
* Waits if necessary for the computation to complete, and then
475
* retrieves its result.
476
*
477
* @return The computed result.
478
*
479
* @throws CancellationException If the computation was cancelled.
480
* @throws ExecutionException If the computation threw an exception.
481
* @throws InterruptedException If the current thread was interrupted
482
* while waiting.
483
*/
484
public final Result get() throws InterruptedException, ExecutionException {
485
return mFuture.get();
486
}
487
488
/**
489
* Waits if necessary for at most the given time for the computation
490
* to complete, and then retrieves its result.
491
*
492
* @param timeout Time to wait before cancelling the operation.
493
* @param unit The time unit for the timeout.
494
*
495
* @return The computed result.
496
*
497
* @throws CancellationException If the computation was cancelled.
498
* @throws ExecutionException If the computation threw an exception.
499
* @throws InterruptedException If the current thread was interrupted
500
* while waiting.
501
* @throws TimeoutException If the wait timed out.
502
*/
503
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
504
ExecutionException, TimeoutException {
505
return mFuture.get(timeout, unit);
506
}
507
508
/**
509
* Executes the task with the specified parameters. The task returns
510
* itself (this) so that the caller can keep a reference to it.
511
*
512
* <p>Note: this function schedules the task on a queue for a single background
513
* thread or pool of threads depending on the platform version. When first
514
* introduced, AsyncTasks were executed serially on a single background thread.
515
* Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
516
* to a pool of threads allowing multiple tasks to operate in parallel. Starting
517
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
518
* executed on a single thread to avoid common application errors caused
519
* by parallel execution. If you truly want parallel execution, you can use
520
* the {@link #executeOnExecutor} version of this method
521
* with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
522
* on its use.
523
*
524
* <p>This method must be invoked on the UI thread.
525
*
526
* @param params The parameters of the task.
527
*
528
* @return This instance of AsyncTask.
529
*
530
* @throws IllegalStateException If {@link #getStatus()} returns either
531
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
532
*
533
* @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
534
* @see #execute(Runnable)
535
*/
536
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
537
return executeOnExecutor(sDefaultExecutor, params);
538
}
539
540
/**
541
* Executes the task with the specified parameters. The task returns
542
* itself (this) so that the caller can keep a reference to it.
543
*
544
* <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
545
* allow multiple tasks to run in parallel on a pool of threads managed by
546
* AsyncTask, however you can also use your own {@link Executor} for custom
547
* behavior.
548
*
549
* <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
550
* a thread pool is generally <em>not</em> what one wants, because the order
551
* of their operation is not defined. For example, if these tasks are used
552
* to modify any state in common (such as writing a file due to a button click),
553
* there are no guarantees on the order of the modifications.
554
* Without careful work it is possible in rare cases for the newer version
555
* of the data to be over-written by an older one, leading to obscure data
556
* loss and stability issues. Such changes are best
557
* executed in serial; to guarantee such work is serialized regardless of
558
* platform version you can use this function with {@link #SERIAL_EXECUTOR}.
559
*
560
* <p>This method must be invoked on the UI thread.
561
*
562
* @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a
563
* convenient process-wide thread pool for tasks that are loosely coupled.
564
* @param params The parameters of the task.
565
*
566
* @return This instance of AsyncTask.
567
*
568
* @throws IllegalStateException If {@link #getStatus()} returns either
569
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
570
*
571
* @see #execute(Object[])
572
*/
573
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
574
Params... params) {
575
if (mStatus != Status.PENDING) {
576
switch (mStatus) {
577
case RUNNING:
578
throw new IllegalStateException("Cannot execute task:"
579
+ " the task is already running.");
580
case FINISHED:
581
throw new IllegalStateException("Cannot execute task:"
582
+ " the task has already been executed "
583
+ "(a task can be executed only once)");
584
}
585
}
586
587
mStatus = Status.RUNNING;
588
589
onPreExecute();
590
591
mWorker.mParams = params;
592
exec.execute(mFuture);
593
594
return this;
595
}
596
597
/**
598
* Convenience version of {@link #execute(Object...)} for use with
599
* a simple Runnable object. See {@link #execute(Object[])} for more
600
* information on the order of execution.
601
*
602
* @see #execute(Object[])
603
* @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
604
*/
605
public static void execute(Runnable runnable) {
606
sDefaultExecutor.execute(runnable);
607
}
608
609
/**
610
* This method can be invoked from {@link #doInBackground} to
611
* publish updates on the UI thread while the background computation is
612
* still running. Each call to this method will trigger the execution of
613
* {@link #onProgressUpdate} on the UI thread.
614
*
615
* {@link #onProgressUpdate} will note be called if the task has been
616
* canceled.
617
*
618
* @param values The progress values to update the UI with.
619
*
620
* @see #onProgressUpdate
621
* @see #doInBackground
622
*/
623
protected final void publishProgress(Progress... values) {
624
if (!isCancelled()) {
625
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
626
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
627
}
628
}
629
630
private void finish(Result result) {
631
if (isCancelled()) {
632
onCancelled(result);
633
} else {
634
onPostExecute(result);
635
}
636
mStatus = Status.FINISHED;
637
}
638
639
private static class InternalHandler extends Handler {
640
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
641
@Override
642
public void handleMessage(Message msg) {
643
AsyncTaskResult result = (AsyncTaskResult) msg.obj;
644
switch (msg.what) {
645
case MESSAGE_POST_RESULT:
646
// There is only one result
647
result.mTask.finish(result.mData[0]);
648
break;
649
case MESSAGE_POST_PROGRESS:
650
result.mTask.onProgressUpdate(result.mData);
651
break;
652
}
653
}
654
}
655
656
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
657
Params[] mParams;
658
}
659
660
@SuppressWarnings({"RawUseOfParameterizedType"})
661
private static class AsyncTaskResult<Data> {
662
final AsyncTask mTask;
663
final Data[] mData;
664
665
AsyncTaskResult(AsyncTask task, Data... data) {
666
mTask = task;
667
mData = data;
668
}
669
}
670
}
671
672