我在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();}
}
}
答案 0 :(得分:3)
我不清楚你可以从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();
答案 1 :(得分:0)
您可以在后台线程中使用Tasks.await(task)
。不要在UI线程中使用它。您还可以为任务Tasks.await(task, 500, TimeUnit.MILLISECONDS);
答案 2 :(得分:-2)
使用getStatus()方法。
while (task.getStatus() != Status.FINISHED);
更好的方法是在split()
方法中调用onPostExecute()
,因为onPostExecute()
无论如何都会在UI线程上运行,而while()
调用会阻止当前线程正在运行。