AsyncTask使用注意事項,asynctask的使用

來源:互聯網
上載者:User

AsyncTask使用注意事項,asynctask的使用

AsyncTask是android內建的一個非同步處理線程 

它帶了很多參數

都很方便使用

但是有一些注意事項

1:

官網說明: 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 package such as ExecutorThreadPoolExecutor and FutureTask.

就是說AsyncTask只適合用於執行一些簡短的程式。如果要長期線程的話還是需要使用後面三個類來支援。

2:

onPreExecute()

doInBackground(Params...),

onProgressUpdate(Progress...)

onPostExecute(Result),

再看它的這個幾個方法

除了第二個 其他3個方法都由主線程調用 可以列印一下線程的ID發現他們和主線程ID一樣

而這4個方法都不能主動調用 不報錯

 

3:

new一個AsyncTask它一會execute一次 如果再次啟動會報錯 只能再new一個

 

4:

用cancel(造句大全)方法後, doInBackgroud方法還是會執行完畢。這就是為什麼官網推薦說不要運行太長時間。

但是我們如何取消doInBackgroup呢

只要在裡面判斷一下  isCancelled(造句)即可,將迴圈條件改成判斷isCancelled(),然後就可以停止doInBackgroup.

那cancel()方法主要取消的什麼方法呢?

主要是後期的

onProgressUpdate(Progress...)

onPostExecute(Result)

這兩個方法都不會執行了 也就是不會去更新UI線程了

本文章由   造句大全 www.zaojuzi.com  整理髮布

相關文章

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.