|
1 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- |
|
2 * This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 package org.mozilla.gecko.util; |
|
7 |
|
8 import android.os.Handler; |
|
9 import android.os.Looper; |
|
10 |
|
11 /** |
|
12 * Executes a background task and publishes the result on the UI thread. |
|
13 * |
|
14 * The standard {@link android.os.AsyncTask} only runs onPostExecute on the |
|
15 * thread it is constructed on, so this is a convenience class for creating |
|
16 * tasks off the UI thread. |
|
17 */ |
|
18 public abstract class UiAsyncTask<Params, Progress, Result> { |
|
19 private volatile boolean mCancelled = false; |
|
20 private final Handler mBackgroundThreadHandler; |
|
21 private static Handler sHandler; |
|
22 |
|
23 /** |
|
24 * Creates a new asynchronous task. |
|
25 * |
|
26 * @param backgroundThreadHandler the handler to execute the background task on |
|
27 */ |
|
28 public UiAsyncTask(Handler backgroundThreadHandler) { |
|
29 mBackgroundThreadHandler = backgroundThreadHandler; |
|
30 } |
|
31 |
|
32 private static synchronized Handler getUiHandler() { |
|
33 if (sHandler == null) { |
|
34 sHandler = new Handler(Looper.getMainLooper()); |
|
35 } |
|
36 return sHandler; |
|
37 } |
|
38 |
|
39 private final class BackgroundTaskRunnable implements Runnable { |
|
40 private Params[] mParams; |
|
41 |
|
42 public BackgroundTaskRunnable(Params... params) { |
|
43 mParams = params; |
|
44 } |
|
45 |
|
46 @Override |
|
47 public void run() { |
|
48 final Result result = doInBackground(mParams); |
|
49 |
|
50 getUiHandler().post(new Runnable() { |
|
51 @Override |
|
52 public void run() { |
|
53 if (mCancelled) |
|
54 onCancelled(); |
|
55 else |
|
56 onPostExecute(result); |
|
57 } |
|
58 }); |
|
59 } |
|
60 } |
|
61 |
|
62 public final void execute(final Params... params) { |
|
63 getUiHandler().post(new Runnable() { |
|
64 @Override |
|
65 public void run() { |
|
66 onPreExecute(); |
|
67 mBackgroundThreadHandler.post(new BackgroundTaskRunnable(params)); |
|
68 } |
|
69 }); |
|
70 } |
|
71 |
|
72 @SuppressWarnings({"UnusedParameters"}) |
|
73 public final boolean cancel(boolean mayInterruptIfRunning) { |
|
74 mCancelled = true; |
|
75 return mCancelled; |
|
76 } |
|
77 |
|
78 public final boolean isCancelled() { |
|
79 return mCancelled; |
|
80 } |
|
81 |
|
82 protected void onPreExecute() { } |
|
83 protected void onPostExecute(Result result) { } |
|
84 protected void onCancelled() { } |
|
85 protected abstract Result doInBackground(Params... params); |
|
86 } |