Ben Lin | 8e91258 | 2016-09-23 14:25:14 -0700 | [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.annotation.CallSuper; |
| 20 | import android.os.AsyncTask; |
| 21 | import android.os.Handler; |
| 22 | |
| 23 | import com.android.documentsui.base.CheckedTask; |
| 24 | import com.android.documentsui.base.DocumentInfo; |
| 25 | |
| 26 | /** |
| 27 | * A {@link CheckedTask} that takes and query SAF to obtain the |
| 28 | * {@link DocumentInfo} of its root document and call supplied callback to handle the |
| 29 | * {@link DocumentInfo}. |
| 30 | */ |
| 31 | public abstract class TimeoutTask<Input, Output> extends CheckedTask<Input, Output> { |
| 32 | private static final int DEFAULT_TIMEOUT = -1; |
| 33 | |
| 34 | private long mTimeout = DEFAULT_TIMEOUT; |
| 35 | |
| 36 | public TimeoutTask(Check check) { |
| 37 | super(check); |
| 38 | } |
| 39 | |
| 40 | public void setTimeout(long timeout) { |
| 41 | mTimeout = timeout; |
| 42 | } |
| 43 | |
| 44 | @CallSuper |
| 45 | @Override |
| 46 | protected void prepare() { |
| 47 | if (mTimeout < 0) { |
| 48 | return; |
| 49 | } |
| 50 | |
| 51 | Handler handler = new Handler(); |
| 52 | handler.postDelayed(() -> { |
| 53 | if (getStatus() == AsyncTask.Status.RUNNING) { |
Ben Lin | bbb7d03 | 2016-11-15 13:35:41 -0800 | [diff] [blame] | 54 | onTimeout(); |
Ben Lin | 8e91258 | 2016-09-23 14:25:14 -0700 | [diff] [blame] | 55 | cancel(true); |
| 56 | this.finish(null); |
| 57 | } |
| 58 | }, mTimeout); |
| 59 | } |
| 60 | |
Ben Lin | 6537acd | 2016-11-16 12:06:21 -0800 | [diff] [blame^] | 61 | /* |
| 62 | * Override this do more proper clean up in case of timeout, such as using |
| 63 | * CancellationSignal#cancel. |
| 64 | */ |
| 65 | protected void onTimeout() {} |
Ben Lin | 8e91258 | 2016-09-23 14:25:14 -0700 | [diff] [blame] | 66 | } |