如何通过构造函数将实现的侦听器传递给AsyncTask?

时间:2018-08-22 18:01:21

标签: java android asynchronous

界面:

public interface OnTaskCompleted{
    void onTaskCompleted(Document doc);
}

为此Activity扩展了Interface

public Activity implements OnTaskCompleted{
   //Activity
}

AsyncTask完成后发送信息。

public MyAsyncTask extends AsyncTask<Object,Object,Object>{ 
    private OnTaskCompleted listener;

    // all your stuff
    public MyAsyncTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    protected void onPostExecute(Object o){
        listener.onTaskCompleted(doc);
    }
}

但是在实例化监听器时如何将其传递给?

public Activity implements OnTaskCompleted{
    //Activity
    @Override
    onTaskCompleted(Object o){
        //Do something in activity
    }
    ...onCreate... {
        asyncTask = new YourTask(???????);
        asyncTask.execute();
    }
}

1 个答案:

答案 0 :(得分:2)

this传递给构造函数:

asyncTask = new MyAsyncTask(this);

您的活动实现了OnTaskCompleted,因此可以传递给MyAsyncTask