今天做项目遇到需要AsyncTask的东西,看了一下文档,这个类很好用,也很简单。
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
这个类被用来在后台执行操作,并且通知UI线程,而不一定需要一个handler线程。
The three types used by an asynchronous task are the following:
When an asynchronous task is executed, the task goes through 4 steps:
当一个task开始执行的时候,这个方法会被调用。这个方法可以不重写,我的那个项目中就没有用到,就看需求了。
在 onPreExecute()后,紧接着执行这个方法。
这个方法在 publishProgress(Progress...)被调用的时候执行。操作的执行时间是不明确的。在后台操作执行的时候,这个方法可以用来在UI显示一些进度或者日志之类的东西。
这个方法在整个操作执行完成后被调用。会获得一个Result对象。
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically(周期地) from doInBackground(Object[]), if possible (inside a loop for instance.)通过调用cancel(boolean),可以在任何时候停止这个task。
在调用这个方法后,isCancelled()将返回true。在这个方法被调用后,在 doInBackground(Object[])之后,onPostExecute(Object) 不会被调用,而是调用onCancelled(Object)。文档上建议在doInBackground(Object[])里周期性的检测isCancelled()的返回值。
There are a few threading rules that must be followed for this class to work properly:
以上内容是 AsyncTask 官方文档的简单翻译,和自己的一些理解。
- EOF -
本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处,尊重他人劳动。
转载请注明:文章转载自 Binkery 技术博客 [https://binkery.com]
本文标题: AsyncTask 官方文档的简单翻译和理解
本文地址: https://binkery.com/archives/52.html