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