AsyncTask and error handling on Android

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

    Another possibility would be to use Object as return type, and in onPostExecute() check for the object type. It is short.

    class MyAsyncTask extends AsyncTask {
    
        @Override
        protected AsyncTaskResult doInBackground(MyInObject... myInObjects) {
            try {
                MyOutObject result;
                // ... do something that produces the result
                return result;
            } catch (Exception e) {
                return e;
            }
        }
    
        protected void onPostExecute(AsyncTaskResult outcome) {
            if (outcome instanceof MyOutObject) {
                MyOutObject result = (MyOutObject) outcome;
                // use the result
            } else if (outcome instanceof Exception) {
                Exception e = (Exception) outcome;
                // show error message
            } else throw new IllegalStateException();
        }
    }
    

提交回复
热议问题