为什么AsyncTask只能完成一项工作?例如,
task = new SubAsyncTask(...); // assume the parameter is correct.
task.execute(...) //
task.execute(...)// calling once again, it throws exeception.
Run Code Online (Sandbox Code Playgroud)
但是,a Handler可以不断执行多项任务:
hd = new Handler(...); // assume the parameter is correct
hd.sendMessage(...); //
hd.sendMessage(...);// no exeception is thrown.
Run Code Online (Sandbox Code Playgroud)
AasyncTask只是一次性工作的对象吗?如果我不想为类似的任务创建多个对象,我应该选择Handler吗?
Handler和AsyncTasks是使用UI/Event Thread实现多线程的方法.
Handler允许向创建它的线程添加消息,并且还允许您在将来的某个时间安排某些runnable执行.
异步任务使您能够实现MultiThreading,而不会将其弄脏到线程中.Async Task提供了一些需要定义以使代码正常工作的方法.在onPreExecute中,您可以定义代码,这些代码需要在后台处理开始之前执行.doInBackground有需要在后台执行的代码,在doInBackground中我们可以通过publishProgress()方法将结果多次发送到事件线程,通知后台处理已经完成,我们可以简单地返回结果.onProgressUpdate()方法从doInBackground方法接收进度更新,该方法通过publishProgress方法发布,并且此方法可以使用此进度更新来更新事件线程,onPostExecute()方法处理doInBackground方法返回的结果.
因此,您不需要在AsyncTask多个TImes上调用execute方法,而是可以调用publishProgress.
| 归档时间: |
|
| 查看次数: |
4110 次 |
| 最近记录: |