gpt4 book ai didi

android - 调用 postExecute 时在 AsyncTask 中添加监听器

转载 作者:行者123 更新时间:2023-11-29 15:44:03 27 4
gpt4 key购买 nike

我有一个 AsyncTask 类。

这是代码。

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 方法时,我想在 Activity 中获取 bool 值。

谢谢。

最佳答案

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

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

关于android - 调用 postExecute 时在 AsyncTask 中添加监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35641843/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com