正如我所說的,這是AsyncTask的正確使用嗎?可以這樣使用AsyncTask:
我的意思是,在不使用任何參數的情況下,將活動上下文傳遞給onPreExecute()
,並且沒有得到返回值的結果,但管理器本身調用onPostExecute()
。
另外還有一件事,Asynctask API Reference提到了onPostExecute()
:「如果任務被取消,將不會調用此方法。」 ,那麼如果在執行doInBackground()
方法時發生SomeException,那麼如何調用onPostExecuted()
?
public class MainClass {
...
//Somewhere in the class, the task is called:
new MyAsyncTask.execute();
...
private class MyAsyncTask extends AsyncTask <Void,Void,Void> {
private MyManager manager;
protected void onPreExecute(){
super.onPreExecute();
//We initialice the members here, passing the context like this:
manager = new Manager(MainClass.this);
manager.initializeMembers();
}
protected void doInBackgroud(Void ...params){
try{
//here we use the long operation task that is inside the manager:
manager.startLongTask();
} catch (SomeException e){
doWhatEverItIsWith(e);
}
return null;
}
protected void onPostExecute (Void result){
super.onPostExecute(result);
//Here we get the result from the manager
handleTheResultFromHere(manager.getResult());
}
}
}
謝謝。