How to handle AsyncTask failure

前端 未结 5 557
轻奢々
轻奢々 2021-01-04 06:09

Is there a specific way to handle failure in an AsyncTask? As far as I can tell the only way is with the return value of task. I\'d like to be able to provide more details o

5条回答
  •  日久生厌
    2021-01-04 06:39

    I modified Nicholas's code a bit, should you want to do something in the UI thread in exception.

    Remember the AsyncTask can only be executed once after instantiated.

    class ErrorHandlingAsyncTask extends AsyncTask<..., ..., ...> {
    
        private Exception exception = null;
    
        protected abstract void onResult(Result result);
    
        protected abstract void onException(Exception e);
    
        protected abstract ... realDoInBackground(...);
    
        @Override
        final protected void onPostExecute(Result result) {
            if(result != null) {
                onResult(result);
            } else {
                onException(exception);
            }
        }
    
        @Override
        protected ... doInBackground(...) {
            try {
                return realDoInBackground(...);
            } catch(Exception e) {
                exception = e;
            }
            return null;
        }
    }
    

提交回复
热议问题