我创建了一个异步任务来调用我的服务器从DB获取数据。

我需要处理从http服务器调用返回的结果。

从我的活动我在许多地方调用异步任务。 所以我不能使用成员variables来访问结果。 有什么办法吗?

public Result CallServer(String params) { try { new MainAynscTask().execute(params); } catch(Exception ex) { ex.printStackTrace(); } return aResultM;//Need to get back the result } private class MainAynscTask extends AsyncTask { @Override protected Result doInBackground(String... ParamsP) { //calling server codes return aResultL; } @Override protected void onPostExecute(Result result) { super.onPostExecute(result); //how i will pass this result where i called this task? }

调用execute()方法后,尝试调用AsyncTask的get()方法。 这对我有用

public Result CallServer(String params) { try { MainAynscTask task = new MainAynscTask(); task.execute(params); Result aResultM = task.get(); //Add this } catch(Exception ex) { ex.printStackTrace(); } return aResultM;//Need to get back the result } ... ...

我可以建议两种方式 –

AsyncTask onPostExecute(Result) 。 请参阅http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result)

发送带有额外结果的广播。

AsyncTask是一个异步任务,因此将结果返回给调用者没有意义。 而是在onPostExecute()处理结果,比如将值设置为TextView等。或者发送广播以便其他一些侦听器可以处理结果。

以下是我如何解决这个问题:

1)创建一个接口类,为完成时执行的方法定义签名:

public interface AsyncIfc { public void onComplete(); }

2)在AsyncTask类上设置一个属性来保存委托方法:

public AsyncIfc completionCode;

3)从AsyncTask中的onPostExecute()触发委托:

completionCode.onComplete();

4)从您的调用逻辑中,将delegate属性设置为匿名方法:

task.completionCode = new AsyncIfc() { @Override public void onComplete() { // Any logic you want to happen after execution } };

执行异步任务时,任务将执行4个步骤:

onPreExecute(),在执行任务之前在UI线程上调用。 此步骤通常用于设置任务,例如通过在用户界面中显示进度条。

doInBackground(Params …),在onPreExecute()完成执行后立即在后台线程上调用。 此步骤用于执行可能需要很长时间的后台计算。 异步任务的参数将传递给此步骤。 计算结果必须由此步骤返回,并将传递回最后一步。 此步骤还可以使用publishProgress(Progress …)发布一个或多个进度单元。 这些值发布在UI线程的onProgressUpdate(Progress …)步骤中。

onProgressUpdate(Progress …),在调用publishProgress(Progress …)后在UI线程上调用。 执行的时间是不确定的。 此方法用于在后台计算仍在执行时显示用户界面中的任何forms的进度。 例如,它可用于为进度条设置animation或在文本字段中显示日志。

onPostExecute(Result), 在后台计算完成后在UI线程上调用。 背景计算的结果作为parameter passing给该步骤。

使用处理程序

在你的活动中

Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { String s=(String)msg.obj; tv.setText(s); } }; //result is soap object in this case. protected void onPostExecute(SoapObject result) { pd.dismiss(); if(result != null) { Message msg=new Message(); msg.obj=result.getProperty(0).toString(); mHandler.sendMessage(msg); }