1 /* 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 17 package com.android.settings; 18 19 import android.os.AsyncTask; 20 21 import androidx.annotation.Nullable; 22 23 import com.android.settingslib.utils.ThreadUtils; 24 25 import java.util.concurrent.Future; 26 27 /** A {@link SidecarFragment} which uses an {@link AsyncTask} to perform background work. */ 28 public abstract class AsyncTaskSidecar<Param, Result> extends SidecarFragment { 29 30 private Future<Result> mAsyncTask; 31 32 @Override onDestroy()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 */ doInBackground(@ullable Param param)46 protected abstract Result doInBackground(@Nullable Param param); 47 48 /** Handles the background task's result. */ onPostExecute(Result result)49 protected void onPostExecute(Result result) {} 50 51 /** Runs the sidecar and sets the state to RUNNING. */ run(@ullable final Param param)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 } 67