Future
是Java API的一部分,而AsyncTask
是Android专用的。事实上,如果你看看在source code of AsyncTask
,你会看到,它实际上采用的是FutureTask
及其实施:
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
的AsyncTask
因此只是短期穿线工作一个辅助类,这也处理一些thread pooling 。我的猜测是,您项目的原创作者熟悉Future
s,但不熟悉AsyncTask
,或者通常不喜欢AsyncTask
。
因为我不喜欢原来的AsyncTask
实施,由于其Exception
处理,我去了一个更好的选择进行搜索,并发现RoboGuice's SafeAsyncTask。在此实现中,回调函数onException(Exception)
可用,但RuntimeException
也会传播到该回调函数。
我认为一个NullPointerException
应该会让应用程序崩溃,并且我稍微修改了这个SafeAsyncTask
来做这件事。结果可以找到here。
谢谢,我怀疑你提到的情况或他们试图“模拟”同步行为。知道Async正在使用FutureTask并且我还没有意识到AsyncTask的异常处理问题。 – stevebot 2015-02-10 17:10:48