0

由于 android doc,该任务只能执行一次。

我正在尝试在 UI-Thread 中运行 HttpClient。但它只允许一次。如果我想从第一次启动时尚未运行的另一个链接获取另一个数据,我该怎么做?直到我在应用程序第一次启动时获得所有数据,这需要很长时间。有谁知道如何解决这个问题?

4

2 回答 2

2

您可以在 AsyncTask 中执行多项操作

protected Void doInBackground(Void param...){
    downloadURL(myFirstUrl);
    downloadURL(mySecondUrl);
}

AsyncTask 只能执行一次。这意味着,如果您创建 AsyncTask 的实例,则只能调用execute()一次。如果要再次执行 AsyncTask,请创建一个新的 AsyncTask:

MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(); //Will work
myAsyncTask.execute(); //Will not work, this is the second time
myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(); //Will work, this is the first execution of a new AsyncTask.
于 2012-11-04T09:09:07.687 回答
2

您正在主线程上运行网络操作。使用异步任务在后台线程中运行网络操作(在后台线程中执行您的 http 请求)。

在这样的异步任务中建立网络:

class WebRequestTask extends AsyncTask{


    protected void onPreExecute() {
    //show a progress dialog to the user or something
    }

    protected void doInBackground() {
        //Do your networking here
    }

    protected void onPostExecute() {
        //do something with your 
       // response and dismiss the progress dialog
    }
  }

  new WebRequestTask().execute();

如果您不知道如何使用异步任务,这里有一些教程供您参考:

http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/

http://www.vogella.com/articles/AndroidPerformance/article.html

以下是来自 Google 的官方文档:

https://developer.android.com/reference/android/os/AsyncTask.html

You can call the async task multiple times whenever needed to perform the download tasks. You can pass parameters to the async task so that you can specify what data it should download (for example by passing a different url each time as a parameter to the async task). In this way, using a modular approach, you can call the same aync task multiple times with different parameters to download the data. The UI thread wont be blocked so the user experience will not be hindered and your code will be thread safe too.

于 2012-11-04T09:13:54.737 回答