0

我有一个 AsynchTask,它在我的 MainActivity 中的一个函数中调用。onPostExecute 方法执行后,控件似乎没有返回到我调用AsynchTask 的函数。

public class MainActivity extends FragmentActivity {

private class GetPlaces extends AsyncTask<AsynchInput,Void,AsynchOutput>{

    protected AsynchOutput doInBackground(AsynchInput... placesURL) {

        ...
    }

    protected void onPostExecute(AsynchOutput result) {
     ....
    }


}


public void showInterestingPlacesNearby(GoogleMap myMap,Location loc){

    ....
    ...

    new GetPlaces().execute(new AsynchInput(myMap,placesSearchStr));


}   

}

我在新的新 GetPlaces().execute 之后编写的代码没有执行。AysnchTask 返回后如何继续。

编辑:我使用 AsynchTask 作为 MainActivity 的内部类。

4

3 回答 3

0

AsyncTask用于UI 线程在后台线程上运行代码。这不像函数调用,并且执行会立即继续执行调用之后的语句.execute()。同时,doInBackground你的 AsyncTask 中的代码在后台线程上执行,运行时不会阻塞 UI 线程。这是预期的行为,没有它使用AsyncTask将毫无意义。

响应异步操作结束的唯一方法是在内部进行-如果您需要对后台代码采取一些行动,onPostExecute您也可以在内部采取行动。onProgressUpdate

所以你的showInterestingPlacesNearby()方法在调用之后不需要做任何事情.execute——你想在那里执行的代码可能应该进入onPostExecute.

或者,您可以使用onProgressUpdate在找到项目时对其进行处理,而不是在一次显示所有内容之前等待整个异步操作完成。为此,您需要publishProgressdoInBackground发现某些东西时使用。

于 2013-06-11T13:08:55.673 回答
0

一个可能的解决方案可能是:获取您在 .execute 之后输入的代码并将其放入私有方法中

private void AfterTask() {
//your code written after .execute here
}

在 onPostExecute 中,只需调用该方法

protected void onPostExecute(AsynchOutput result) {
    AfterTask();
}
于 2013-06-11T13:16:57.797 回答
0
myTask.execute("url");
String result = "";
try {
      result = myTask.get().toString();
} catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
}catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
}
于 2017-07-11T16:21:51.673 回答