Android 中的AsyncTask

來源:互聯網
上載者:User

標籤: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.)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.