blob: 31c8298e1f7ccc1a0a80595b0ddb7a5ec63a1121 [file] [log] [blame]
Jiashen Wang7840ae72020-10-29 16:55:43 -07001/*
2 * Copyright (C) 2020 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
17package com.android.settings;
18
19import android.os.AsyncTask;
20
21import androidx.annotation.Nullable;
22
23import com.android.settingslib.utils.ThreadUtils;
24
25import java.util.concurrent.Future;
26
27/** A {@link SidecarFragment} which uses an {@link AsyncTask} to perform background work. */
28public abstract class AsyncTaskSidecar<Param, Result> extends SidecarFragment {
29
30 private Future<Result> mAsyncTask;
31
32 @Override
33 public void onDestroy() {
34 if (mAsyncTask != null) {
35 mAsyncTask.cancel(true /* mayInterruptIfRunning */);
36 }
37
38 super.onDestroy();
39 }
40
41 /**
42 * Executes the background task.
43 *
44 * @param param parameters passed in from {@link #run}
45 */
46 protected abstract Result doInBackground(@Nullable Param param);
47
48 /** Handles the background task's result. */
49 protected void onPostExecute(Result result) {}
50
51 /** Runs the sidecar and sets the state to RUNNING. */
52 public void run(@Nullable final Param param) {
53 setState(State.RUNNING, Substate.UNUSED);
54
55 if (mAsyncTask != null) {
56 mAsyncTask.cancel(true /* mayInterruptIfRunning */);
57 }
58
59 mAsyncTask =
60 ThreadUtils.postOnBackgroundThread(
61 () -> {
62 Result result = doInBackground(param);
63 ThreadUtils.postOnMainThread(() -> onPostExecute(result));
64 });
65 }
66}