AsyncTask and error handling on Android

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

    Actually, AsyncTask use FutureTask & Executor, FutureTask support exception-chain First let's define a helper class

    public static class AsyncFutureTask extends FutureTask {
    
        public AsyncFutureTask(@NonNull Callable callable) {
            super(callable);
        }
    
        public AsyncFutureTask execute(@NonNull Executor executor) {
            executor.execute(this);
            return this;
        }
    
        public AsyncFutureTask execute() {
            return execute(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    
        @Override
        protected void done() {
            super.done();
            //work done, complete or abort or any exception happen
        }
    }
    

    Second, let's use

        try {
            Log.d(TAG, new AsyncFutureTask(new Callable() {
                @Override
                public String call() throws Exception {
                    //throw Exception in worker thread
                    throw new Exception("TEST");
                }
            }).execute().get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            //catch the exception throw by worker thread in main thread
            e.printStackTrace();
        }
    

提交回复
热议问题