Steve McKay | c7dc0cf | 2016-02-04 12:15:22 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2016 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.android.documentsui; |
| 18 | |
| 19 | import android.app.Activity; |
| 20 | import android.os.AsyncTask; |
| 21 | |
| 22 | /** |
| 23 | * An {@link AsyncTask} that guards work with checks that a paired {@link Activity} |
| 24 | * is still alive. Instances of this class make no progress. |
| 25 | * |
| 26 | * <p>Use this type of task for greater safety when executing tasks that might complete |
| 27 | * after an Activity is destroyed. |
| 28 | * |
| 29 | * <p>Also useful as tasks can be static, limiting scope, but still have access to |
| 30 | * the owning class (by way the A template and the mActivity field). |
| 31 | * |
| 32 | * @template Owner Activity type. |
| 33 | * @template Input input type |
| 34 | * @template Output output type |
| 35 | */ |
| 36 | abstract class PairedTask<Owner extends Activity, Input, Output> |
| 37 | extends AsyncTask<Input, Void, Output> { |
| 38 | |
| 39 | protected final Owner mOwner; |
| 40 | |
| 41 | public PairedTask(Owner owner) { |
| 42 | mOwner = owner; |
| 43 | } |
| 44 | |
| 45 | /** Called prior to run being executed. Analogous to {@link AsyncTask#onPreExecute} */ |
| 46 | void prepare() {} |
| 47 | |
| 48 | /** Analogous to {@link AsyncTask#doInBackground} */ |
| 49 | abstract Output run(Input... input); |
| 50 | |
| 51 | /** Analogous to {@link AsyncTask#onPostExecute} */ |
| 52 | abstract void finish(Output output); |
| 53 | |
| 54 | @Override |
| 55 | final protected void onPreExecute() { |
| 56 | if (mOwner.isDestroyed()) { |
| 57 | return; |
| 58 | } |
| 59 | prepare(); |
| 60 | } |
| 61 | |
| 62 | @Override |
| 63 | final protected Output doInBackground(Input... input) { |
| 64 | if (mOwner.isDestroyed()) { |
| 65 | return null; |
| 66 | } |
| 67 | return run(input); |
| 68 | } |
| 69 | |
| 70 | @Override |
| 71 | final protected void onPostExecute(Output result) { |
| 72 | if (mOwner.isDestroyed()) { |
| 73 | return; |
| 74 | } |
| 75 | finish(result); |
| 76 | } |
| 77 | } |