Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dkajiwara-asnet/da7fb990aee7667c50de to your computer and use it in GitHub Desktop.
Save dkajiwara-asnet/da7fb990aee7667c50de to your computer and use it in GitHub Desktop.
タイムアウトするAsyncTask

#AsyncTaskの処理をタイムアウトさせる こんな感じ

new ExAsyncTask().setTimeOut(1000).execute();
public class ExAsyncTask extends AsyncTask<Void, Void, Void>{
    /** TAG.*/
    private static final String TAG = ExAsyncTask.class.getSimpleName();
    /** Time-Out(milliseconds).*/
    private long mTimeOut = -1;
    /**
    * Invoked when the running task has timed out.
    */
    private Runnable mTimeOutTask = new Runnable() {
        @Override
        public void run() {
            try {
                get(mTimeOut, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Log.e(TAG, null, e);
            } catch (ExecutionException e) {
                Log.e(TAG, null, e);
            } catch (TimeoutException e) {
                Log.i(TAG, "Running task has timed out!!", e);
                if (isCancelled() && getStatus() == Status.RUNNING) {
                    ExAsyncTask.this.cancel(true);
                }
            }
        }
    };

    @Override
    protected Void doInBackground(Void... params) {
        if (mTimeOut > 0) {
            new Thread(mTimeOutTask).start();
        }
        //do someting
        return null;
    }

    /**
    * Set the time-out.
    * @param timeOut milliseconds
    * @return this
    */
    public ExAsyncTask setTimeOut(long timeOut) {
        mTimeOut = timeOut;
        return this;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment