gpt4 book ai didi

java - Android AsyncTask 等待完成

转载 作者:行者123 更新时间:2023-12-01 10:38:40 25 4
gpt4 key购买 nike

我正在 Android 应用程序中使用 AsyncTask 调用 Web 服务,但我不知道如何等待 onPostExecute 完成:

//Call Async Web Service here 
AsyncCallWS task = new AsyncCallWS();
task.execute();
//Need to wait to fill this in ** Its not waiting.
String sCall = rslt;
String[] aCall = sCall.split("//|");

private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
@Override
protected Void doInBackground(Void... params) {
Log.i(TAG, "doInBackground");
GetURL();
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i(TAG, "onPostExecute");
try{
//Results HERE
rslt = resultString.toString();
}
catch(Exception ex)
{rslt = ex.toString()+ "|" + ex.toString();}

}
}

最佳答案

我不清楚你不能/不想从 onPostExecute 做什么,但是如果你想执行与任务不耦合的东西(这样你就可以运行任务),你可以使用回调从任何地方)

private class OnFinishedListener {
void onFinished(String rslt);
}

private class AsyncCallWS extends AsyncTask<Void, Void, Void> {

private OnFinishedListener mAfter;

public AsyncCallWS(OnFinishedListener after) {
mAfter = after;
}

...

@Override
protected void onPostExecute(Void result) {
....
if (mAfter != null) {
//you didnt illustrate what resultString is, you might
//want this to be the returned value from doInBackground
mAfter.onFinished(resultString.toString());
}
}

}

使用

new AsyncCallWS(new OnFinishedListener {
public void onFinished(String rslt) {
//for example
String sCall = rslt;
String[] aCall = sCall.split("//|");
}
}).execute();

关于java - Android AsyncTask 等待完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34535066/

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