我正在使用AsyncTask类,但我将它用作公共类。我想在完成执行后运行一些代码,但我无法弄清楚如何在类之外执行它。例如:
exampleAsyncTaskClass.execute(params);
//What can I write here to execute code after the AsyncTask is completed
无论如何,我可以在任务完成后执行代码而不使用受保护的onPostExecute方法。或者有没有办法可以让这种方法不受保护?
答案 0 :(得分:0)
您可以将处理程序传递给任务的构造函数,并在任务完成时调用它。
看起来像这样:
public class SomeTask extends AsyncTask<Object, Object, Object>{
private OnPostExecuteHandler handler;
public SomeTask(OnPostExecuteHandler handler) {
this.handler = handler;
}
@Override protected Object doInBackground(Object... params) {
return null;
}
@Override protected void onPostExecute(Object o) {
handler.runOnFinish();
}
public interface OnPostExecuteHandler{
void runOnFinish();
}
}
用法:
new SomeTask(new SomeTask.OnPostExecuteHandler() {
@Override public void runOnFinish() {
//will be called when the task is finished
}
}).execute(someParams);
答案 1 :(得分:0)
你可以做这样的事情......
public class Myclass{
boolean isTaskFinished;
if(isfinsihed){
//execute some code
}
ExampleTask exampe=new ExampleTask();
example.execute;
class ExampleTask extends AsyncTask<Object, Object, Object>{
private OnPostExecuteHandler handler;
public ExampleTask (OnPostExecuteHandler handler) {
this.handler = handler;
}
@Override protected Object doInBackground(Object... params) {
return null;
}
@Override protected void onPostExecute(Object o) {
handler.runOnFinish();
}
public interface OnPostExecuteHandler{
void runOnFinish();
isFinished=true:
}
}
}