blob: 57b119e8fbe9e23ef1d5c8923e9221ba233df4fa [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;
25import com.android.documentsui.base.DocumentInfo;
26
27/**
28 * A {@link CheckedTask} that takes and query SAF to obtain the
29 * {@link DocumentInfo} of its root document and call supplied callback to handle the
30 * {@link DocumentInfo}.
31 */
32public abstract class TimeoutTask<Input, Output> extends CheckedTask<Input, Output> {
33 private static final int DEFAULT_TIMEOUT = -1;
34
35 private long mTimeout = DEFAULT_TIMEOUT;
36
37 public TimeoutTask(Check check) {
38 super(check);
39 }
40
41 public void setTimeout(long timeout) {
42 mTimeout = timeout;
43 }
44
45 @CallSuper
46 @Override
47 protected void prepare() {
48 if (mTimeout < 0) {
49 return;
50 }
51
Ben Line9abd2d2016-12-06 11:39:52 -080052 // Need to initialize handler to main Looper so it can initialize correctly in test cases
53 // Instrumentation threads don't have looper initialized
54 Handler handler = new Handler(Looper.getMainLooper());
Ben Lin8e912582016-09-23 14:25:14 -070055 handler.postDelayed(() -> {
56 if (getStatus() == AsyncTask.Status.RUNNING) {
Ben Linbbb7d032016-11-15 13:35:41 -080057 onTimeout();
Ben Lin8e912582016-09-23 14:25:14 -070058 cancel(true);
59 this.finish(null);
60 }
61 }, mTimeout);
62 }
63
Ben Lin6537acd2016-11-16 12:06:21 -080064 /*
65 * Override this do more proper clean up in case of timeout, such as using
66 * CancellationSignal#cancel.
67 */
68 protected void onTimeout() {}
Ben Lin8e912582016-09-23 14:25:14 -070069}