我们可以在Asynctask中多次运行HTTPCLIENT吗?



由于Android Doc,该任务只能执行一次。

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

您正在主线程上运行网络操作。使用异步任务在背景线程中运行网络操作(在背景线程中执行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-developmentthreadthreading-part-2-async-tasks/

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

这是Google的官方文档:

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

您可以在需要执行下载任务时多次调用异步任务。您可以将参数传递到异步任务,以便您可以指定应该下载的数据(例如,每次将其他URL作为参数传递给异步任务)。通过这种方式,使用模块化方法,您可以多次调用具有不同参数的同一AYNC任务以下载数据。UI线程不会被阻止,以免用户体验受到阻碍,并且您的代码也将是安全的。

您可以在asynctask中进行多个操作

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

只能执行一次异步。这意味着,如果您创建一个异步箱的实例,则只能调用execute()一次。如果您想再次执行异步性,请创建一个新的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.

最新更新