Home | History | Annotate | Download | only in documentsui
      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 import android.os.Looper;
     23 
     24 import com.android.documentsui.base.CheckedTask;
     25 
     26 /**
     27  * A {@link CheckedTask} that will timeout after a certain period of time, and do any properly clean
     28  * up necessary before ending itself.
     29  */
     30 public abstract class TimeoutTask<Input, Output> extends CheckedTask<Input, Output> {
     31     public static final int DEFAULT_TIMEOUT = -1;
     32 
     33     private long mTimeout = DEFAULT_TIMEOUT;
     34 
     35     public TimeoutTask(Check check, long timeout) {
     36         super(check);
     37         mTimeout = timeout;
     38     }
     39 
     40     @CallSuper
     41     @Override
     42     protected void prepare() {
     43         if (mTimeout < 0) {
     44             return;
     45         }
     46 
     47         // 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());
     50         handler.postDelayed(() -> {
     51             if (getStatus() == AsyncTask.Status.RUNNING) {
     52                 onTimeout();
     53                 cancel(true);
     54                 this.finish(null);
     55             }
     56         }, mTimeout);
     57     }
     58 
     59     /*
     60      * Override this do more proper clean up in case of timeout, such as using
     61      * CancellationSignal#cancel.
     62      */
     63     protected void onTimeout() {}
     64 }
     65