How to handle AsyncTask failure

前端 未结 5 562
轻奢々
轻奢々 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

    You can simply save the exception in a field and check it in onPostExecute() (to ensure that any error handling code is run on the UI thread). Something like:

    new AsyncTask() {
        Exception error;
    
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                 // do work
                 return true;
            } catch (Exception e) {
                error = e;
    
                return false;
            } 
        }
    
        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                Toast.makeText(ctx, "Success!",
                    Toast.LENGTH_SHORT).show();
             } else {
                if (error != null) {
                    Toast.makeText(ctx, error.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    

    }

提交回复
热议问题