在AsyncTask的添加侦听器调用postExecute时 [英] Add listener in AsyncTask when called postExecute

查看:126
本文介绍了在AsyncTask的添加侦听器调用postExecute时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个AsyncTask的类。

I have a AsyncTask class.

这里是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);
    }
}

在叫onPostExecute的方法,我想获得活动布尔值。

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

感谢。

推荐答案

您需要使用一个回调引用,然后通过它传递的信息。

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

这篇关于在AsyncTask的添加侦听器调用postExecute时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆