AsyncTask and error handling on Android

前端 未结 12 2158
失恋的感觉
失恋的感觉 2020-11-27 10:32

I\'m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the

12条回答
  •  失恋的感觉
    2020-11-27 10:57

    When I feel the need to handle Exceptions in AsyncTask properly, I use this as super class:

    public abstract class ExceptionAsyncTask extends AsyncTask {
    
        private Exception exception=null;
        private Params[] params;
    
        @Override
        final protected Result doInBackground(Params... params) {
            try {
                this.params = params; 
                return doInBackground();
            }
            catch (Exception e) {
                exception = e;
                return null;
            }
        }
    
        abstract protected Result doInBackground() throws Exception;
    
        @Override
        final protected void onPostExecute(Result result) {
            super.onPostExecute(result);
            onPostExecute(exception, result);
        }
    
        abstract protected void onPostExecute(Exception exception, Result result);
    
        public Params[] getParams() {
            return params;
        }
    
    }
    

    As normal, you override doInBackground in your subclass to do background work, happily throwing Exceptions where needed. You are then forced to implement onPostExecute (because it's abstract) and this gently reminds you to handle all types of Exception, which are passed as parameter. In most cases, Exceptions lead to some type of ui output, so onPostExecute is a perfect place to do that.

提交回复
热议问题