AsyncTask and error handling on Android

前端 未结 12 2159
失恋的感觉
失恋的感觉 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 11:02

    I made my own AsyncTask subclass with an interface that defines callbacks for success and failure. So if an exception is thrown in your AsyncTask, the onFailure function gets passed the exception, otherwise the onSuccess callback gets passed your result. Why android doesn't have something better available is beyond me.

    public class SafeAsyncTask
    extends AsyncTask  {
        protected Exception cancelledForEx = null;
        protected SafeAsyncTaskInterface callbackInterface;
    
        public interface SafeAsyncTaskInterface  {
            public Object backgroundTask(cbInBackgroundType[] params) throws Exception;
            public void onCancel(cbResultType result);
            public void onFailure(Exception ex);
            public void onSuccess(cbResultType result);
        }
    
        @Override
        protected void onPreExecute() {
            this.callbackInterface = (SafeAsyncTaskInterface) this;
        }
    
        @Override
        protected resultType doInBackground(inBackgroundType... params) {
            try {
                return (resultType) this.callbackInterface.backgroundTask(params);
            } catch (Exception ex) {
                this.cancelledForEx = ex;
                this.cancel(false);
                return null;
            }
        }
    
        @Override
        protected void onCancelled(resultType result) {
            if(this.cancelledForEx != null) {
                this.callbackInterface.onFailure(this.cancelledForEx);
            } else {
                this.callbackInterface.onCancel(result);
            }
        }
    
        @Override
        protected void onPostExecute(resultType result) {
            this.callbackInterface.onSuccess(result);
        }
    }
    

提交回复
热议问题