从AsyncTask外部调用AsyncTask onPostExecute

时间:2014-06-26 11:54:44

标签: android android-asynctask

我想在我的应用程序的不同位置使用相同的AsyncTask,我希望每个都有一个不同的 onPostExecute 。是否可以从 onCreate 方法而不是从AsyncTask类调用它们?

类似的东西:

new AsyncTCP.execute()
onPostExecute(){
//DO STUFF
}

2 个答案:

答案 0 :(得分:4)

只需创建一个AsyncTask,但不会覆盖onPostExecute方法

public class YourTask extends AsyncTask<Whatever, Whatever, Whatever> {

    @Override
    protected Whatever doInBackground(Whatever... whatever) {
        // whatever
        return whatever;
    }

}

然后当您需要onPostExecute的不同实现时,创建匿名任务或后代类并使用它

task = new YourTask() {

    @Override
    protected void onPostExcecute(Whatever result) {
        //whatever
    }

};
task.execute();

或更好

public class YourTaskAnother extends YourTask {

    // just override onPostExecute here

    @Override
    protected void onPostExcecute(Whatever result) {
        //whatever
    }
}

task = new YourTaskAnother();
task.execute();

答案 1 :(得分:0)

您可以做的是在onPostExecute()方法中添加一个switch case,具体取决于所有可能的场景。然后在AyncTask中添加一个构造函数,您可以使用该构造函数传递该类型。

DownloadTask extends AsyncTask ...
{
    int postExecuteType; 
    public DownloadTask(int type) {
        this.postExecuteType = type; 
    }
...

    protected void onPostExecuted()
    {
        switch(type) {
            case 1:
            break;
        }
    }

}

现在只需致电newDownloadTask(1).execute();