Add listener in AsyncTask when called postExecute

拥有回忆 提交于 2019-12-24 13:54:06

问题


I have a AsyncTask class.

here is code.

private class WaitSec extends AsyncTask<Void, Void, Boolean>{
    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(CheckSomeUtil.isItOk()) {
            return true;
        } else {
            return false;
        }
    }
    @Override
    protected void onPostExecute(Boolean aBoolean) {
        if(aBoolean)
            // in this line. is i want to set listener.
        super.onPostExecute(aBoolean);
    }
}

When called onPostExecute method, i'd like to get boolean value in activity.

Thanks.


回答1:


You need to use a callback reference and then pass the information through it.

private class WaitSec extends AsyncTask<Void, Void, Boolean>{
public AsyncTaskCallback callback = null;

public WaitSec(AsyncTaskCallback callback){
        this.callback = callback;
}

@Override
protected Boolean doInBackground(Void... params) {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if(CheckSomeUtil.isItOk()) {
        return true;
    } else {
        return false;
    }
}
@Override
protected void onPostExecute(Boolean aBoolean) {
    if(aBoolean)
        // in this line. is i want to set listener.
      if(callback != null) {
          callback.onPostExecute(aBoolean);
      }
    super.onPostExecute(aBoolean);
}

public interface AsyncTaskCallback {
        void onPostExecute(Boolean aBoolean);
}
}

Your Activity.java

public class YourActivity implements AsyncTaskCallback{
   private WaitSec asyncTask;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    asyncTask  = new WaitSec(this);
    asyncTask.execute();
  }

  void onPostExecute(Boolean aBoolean){
     // get the boolean here and do what ever you want.
  }
}



回答2:


Why not have this async task as an inner class in your activity so you can access methods of your activity.

Warning : if not handled properly async tasks can hold on to your activty instance and will not let it be garbage collected.



来源:https://stackoverflow.com/questions/35641843/add-listener-in-asynctask-when-called-postexecute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!