blob: 9e7bbb810a182acf0dec5a84fe7fb70aebcb1cfe [file] [log] [blame]
Ben Lin8e912582016-09-23 14:25:14 -07001/*
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
17package com.android.documentsui;
18
19import android.annotation.CallSuper;
20import android.os.AsyncTask;
21import android.os.Handler;
Ben Line9abd2d2016-12-06 11:39:52 -080022import android.os.Looper;
Ben Lin8e912582016-09-23 14:25:14 -070023
24import com.android.documentsui.base.CheckedTask;
Ben Lin8e912582016-09-23 14:25:14 -070025
26/**
Ben Lin30b0dc12017-03-07 15:37:16 -080027 * A {@link CheckedTask} that will timeout after a certain period of time, and do any properly clean
28 * up necessary before ending itself.
Ben Lin8e912582016-09-23 14:25:14 -070029 */
30public abstract class TimeoutTask<Input, Output> extends CheckedTask<Input, Output> {
Ben Lin30b0dc12017-03-07 15:37:16 -080031 public static final int DEFAULT_TIMEOUT = -1;
Ben Lin8e912582016-09-23 14:25:14 -070032
33 private long mTimeout = DEFAULT_TIMEOUT;
34
Ben Lin30b0dc12017-03-07 15:37:16 -080035 public TimeoutTask(Check check, long timeout) {
Ben Lin8e912582016-09-23 14:25:14 -070036 super(check);
Ben Lin8e912582016-09-23 14:25:14 -070037 mTimeout = timeout;
38 }
39
40 @CallSuper
41 @Override
42 protected void prepare() {
43 if (mTimeout < 0) {
44 return;
45 }
46
Ben Line9abd2d2016-12-06 11:39:52 -080047 // Need to initialize handler to main Looper so it can initialize correctly in test cases
48 // Instrumentation threads don't have looper initialized
49 Handler handler = new Handler(Looper.getMainLooper());
Ben Lin8e912582016-09-23 14:25:14 -070050 handler.postDelayed(() -> {
51 if (getStatus() == AsyncTask.Status.RUNNING) {
Ben Linbbb7d032016-11-15 13:35:41 -080052 onTimeout();
Ben Lin8e912582016-09-23 14:25:14 -070053 cancel(true);
54 this.finish(null);
55 }
56 }, mTimeout);
57 }
58
Ben Lin6537acd2016-11-16 12:06:21 -080059 /*
60 * Override this do more proper clean up in case of timeout, such as using
61 * CancellationSignal#cancel.
62 */
63 protected void onTimeout() {}
Ben Lin8e912582016-09-23 14:25:14 -070064}