AsyncTask and error handling on Android

前端 未结 12 2174
失恋的感觉
失恋的感觉 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:09

    This simple class can help you

    public abstract class ExceptionAsyncTask extends AsyncTask {
        private Except thrown;
    
        @SuppressWarnings("unchecked")
        @Override
        /**
         * Do not override this method, override doInBackgroundWithException instead
         */
        protected Result doInBackground(Param... params) {
            Result res = null;
            try {
                res = doInBackgroundWithException(params);
            } catch (Throwable e) {
                thrown = (Except) e;
            }
            return res;
        }
    
        protected abstract Result doInBackgroundWithException(Param... params) throws Except;
    
        @Override
        /**
         * Don not override this method, override void onPostExecute(Result result, Except exception) instead
         */
        protected void onPostExecute(Result result) {
            onPostExecute(result, thrown);
            super.onPostExecute(result);
        }
    
        protected abstract void onPostExecute(Result result, Except exception);
    }
    

提交回复
热议问题