0

正如我所说,这是 AsyncTask 的正确使用吗?

我的意思是,不使用任何参数,在 上传递活动上下文onPreExecute(),并且没有得到doInBackground()返回值的结果,而是一旦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());
        }
    }
}

谢谢你。

4

2 回答 2

1

像这样使用 AsyncTask 没有问题。您不必使用doInBackground返回值。关于第二个问题,onPostExecute即使出现异常也会调用 yes 。如果您不想调用它,则必须使用MyAsyncTask.cancel(true)

于 2012-10-05T11:46:49.473 回答
1

正如我所说,这是 AsyncTask 的正确使用吗?

是的,可以将 Activity 上下文传递进去onPreExecute(),然后将数据加载doInBackgroud()onPostExecute().

那么如果 SomeException 在执行 doInBackground() 方法时发生,¿是否调用了 onPostExecuted()?

是的,onPreExecute()如果您在doInBackgroud(). 您必须检查要加载的数据,以onPreExecute()检查数据是否不为空并更新 UI。

NOTE:

永远不要尝试从中更新 UI,doInBackgroud()因为您无法从非 UI 线程更新 UI。替代方法是使用HandlerrunOnUIThread()用于从非 UI 线程更新 UI。

于 2012-10-05T11:48:23.887 回答