请告诉我写这个的最好方法。
我需要一个通用的 AsyncTask 用于 web 服务调用,并处理所有可能的错误。也是用于更新 UI/显示错误消息的回调。
我发现了一些方法:
- 通过将通用参数添加到异步任务
- 将 asynctask 设为抽象
- 用于处理错误给处理程序对象。
请告诉我写这个的最好方法。
我需要一个通用的 AsyncTask 用于 web 服务调用,并处理所有可能的错误。也是用于更新 UI/显示错误消息的回调。
我发现了一些方法:
This is actually very easy to do with an AsyncTask
.
AsyncTask
has 4 functions. 3 of them run on the UI Thread so you can update the UI as much as you like. 1 of the functions runs in the background so you can do things that take as long as is necessary, such as calling your webservice.
You do not need a formal callback function. AsyncTask.onPostExecute()
handles this for you.
There is a great example in the Android documentation that shows how to download a file exactly as you are trying to do with the webservices connection. You will extend AsyncTask
and create your own DownloadFilesTask
just like in the example.
The whole thing is started with a single line of code:
new DownloadFilesTask().execute(...)
The four functions are:
ProgressBar
or other
UI elements.publishProgress()
as often as you
like. That will internally call onProgressUpdate()
where you can
incrementally update the UI, or your ProgressBar
, if you want.ProgressBar
. This function only gets called in response to calling
publishProgress()
from doInBackground()
.dismiss()
your ProgressBar
, update
the UI, process any errors saved in doInBackground()
, and jump to
the next section of your code.Error Handling:
All errors are trapped in doInBackground()
. You should save an int errorCode
and/or String errorMessage
in your DownloadFilesTask
class, and return;
from doInBackground()
when an error occurs. Then, process and report the error in onPostExecute()
.
See this question for several answers. They all involve storing any exception thrown by doInBackground
in a field and checking it in onPostExecute
. I like this answer posted by @dongshengcn, which encapsulates this into a subclass of AsyncTask
, then you can override onResult
and/or onException
as necessary.