Skip to content Skip to sidebar Skip to footer

Add Listener In Asynctask When Called Postexecute

I have a AsyncTask class. here is code. private class WaitSec extends AsyncTask{ @Override protected Boolean doInBackground(Void... params) {

Solution 1:

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

privateclassWaitSecextendsAsyncTask<Void, Void, Boolean>{
publicAsyncTaskCallback callback = null;

publicWaitSec(AsyncTaskCallback callback){
        this.callback = callback;
}

@OverrideprotectedBooleandoInBackground(Void... params) {
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if(CheckSomeUtil.isItOk()) {
        returntrue;
    } else {
        returnfalse;
    }
}
@OverrideprotectedvoidonPostExecute(Boolean aBoolean) {
    if(aBoolean)
        // in this line. is i want to set listener.if(callback != null) {
          callback.onPostExecute(aBoolean);
      }
    super.onPostExecute(aBoolean);
}

publicinterfaceAsyncTaskCallback {
        voidonPostExecute(Boolean aBoolean);
}
}

YourActivity.javapublicclassYourActivityimplementsAsyncTaskCallback{
   privateWaitSec asyncTask;

  @OverridepublicvoidonCreate(Bundle savedInstanceState) {
    asyncTask  = newWaitSec(this);
    asyncTask.execute();
  }

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

Solution 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.

Post a Comment for "Add Listener In Asynctask When Called Postexecute"