问题
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