標籤:android des http java 使用 strong
在後台下載圖片,下載完成後更新UI是一個很常見的需求。在沒有AsyncTask類之前,我們需要寫許多thread和Handler的代碼去實現這個功能,有了AsyncTask,一切變得簡單了。下面摘抄Google官方介紹:
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.
可以看出AsyncTask並沒有引入底層thread技術,僅僅是對Thread 和 Handler的利用而已。並且使用場合也有局限,最多在後台運行幾秒,過長運行不應該使用(會產生什麼問題?)。
使用AsyncTask必須建立子類,複寫指定方法。其中doInBackground和onPostExecute是2個主要的方法。doInBackground在子線程中執行,裡面應該寫些耗時的方法,onPostExecute在doInBackground完成後在主線程中調用。doInBackground,onPostExecute 分別在子線程和主線程調用,就是AsyncTask的特點。
There are a few threading rules that must be followed for this class to work properly:
- The AsyncTask class must be loaded on the UI thread. This is done automatically as of
JELLY_BEAN.
- The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
- Do not call
onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
- The task can be executed only once (an exception will be thrown if a second execution is attempted.)