Android 可以这样使用AsyncTask吗:
正如我所说,这是AsyncTask的正确用法吗 我的意思是,在不使用任何参数的情况下,在Android 可以这样使用AsyncTask吗:,android,android-asynctask,Android,Android Asynctask,正如我所说,这是AsyncTask的正确用法吗 我的意思是,在不使用任何参数的情况下,在onPreExecute()上传递活动上下文,并且不获取doInBackground()返回值的结果,而是在调用onPostExecute()后获取管理器本身 还有一件事,Asynctask API引用了关于onPostExecute():“如果任务被取消,将不会调用此方法。”,那么,如果在执行doInBackground()方法时发生异常,会调用onPostExecuted()吗 public class
onPreExecute()
上传递活动上下文,并且不获取doInBackground()
返回值的结果,而是在调用onPostExecute()
后获取管理器本身
还有一件事,Asynctask API引用了关于onPostExecute()
:“如果任务被取消,将不会调用此方法。”,那么,如果在执行doInBackground()
方法时发生异常,会调用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());
}
}
}
public类MainClass{
...
//在类中的某个位置,该任务称为:
新建MyAsyncTask.execute();
...
私有类MyAsyncTask扩展了AsyncTask{
私人经理;
受保护的void onPreExecute(){
super.onPreExecute();
//我们在这里初始化成员,传递上下文如下:
经理=新经理(MainClass.this);
manager.initializeMembers();
}
受保护的void doinbackground(void…参数){
试一试{
//在这里,我们使用管理器中的长操作任务:
manager.task();
}捕获(某些例外){
(e)每一项;
}
返回null;
}
受保护的void onPostExecute(void结果){
super.onPostExecute(结果);
//这是我们从经理那里得到的结果
handleTheResultFromHere(manager.getResult());
}
}
}
谢谢。像这样使用AsyncTask没有问题。您不必使用
doInBackground
返回值。关于第二个问题,即使出现异常,也将调用yesonPostExecute
。如果不想调用它,则必须使用MyAsyncTask.cancel(true)
正如我所说,这是AsyncTask的正确用法吗
是的,可以在onPreExecute()
中传递活动上下文,然后在doinbackground()
中加载数据,并在onPostExecute()中更新UI
那么,如果在执行
doInBackground()方法,是否调用onPostExecuted()
是的,onPreExecute()
如果在doinbackground()
中遇到任何异常,将调用onPreExecute()。您必须检查要加载到onPreExecute()
中的数据,检查数据是否为空并更新UI
NOTE:
永远不要尝试从doInBackgroud()
更新UI,这会给您带来异常,因为您无法从非UI线程更新UI。另一种方法是使用处理程序
或runOnUIThread()
从非UI线程更新UI