關於AsyncTask的注意事項。

來源:互聯網
上載者:User

 

一個非同步任務的執行一般包括以下幾個步驟:

1.execute(Params... params),執行一個非同步任務,需要我們在代碼中調用此方法,觸發非同步任務的執行。

2.onPreExecute(),在execute(Params... params)被調用後立即執行,一般用來在執行背景工作前對UI做一些標記。

3.doInBackground(Params... params),在onPreExecute()完成後立即執行,用於執行較為費時的操作,此方法將接收輸入參數和返回計算結果。在執行過程中可以調用publishProgress(Progress... values)來更新進度資訊。

4.onProgressUpdate(Progress... values),在調用publishProgress(Progress... values)時,此方法被執行,直接將進度資訊更新到UI組件上。

5.onPostExecute(Result result),當後台操作結束時,此方法將會被調用,計算結果將做為參數傳遞到此方法中,直接將結果顯示到UI組件上。

 

注意事項:

doInBackground中需要一個條件來操作Thread.sleep(int).否則只會執行一次。

AsyncTask適合處理短時間的操作,長時間的操作,比如下載一個很大的視頻,這就需要你使用自己的線程來下載。

package com.example.mediaplayerproject;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.widget.TextView;public class AsyTest extends Activity {private TextView show = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);this.setContentView(R.layout.asy);show = (TextView) findViewById(R.id.show);new asyImpl().execute(1000);}private class asyImpl extends AsyncTask<Integer, Integer, String> {@Overrideprotected void onPostExecute(String result) {super.onPostExecute(result);}@Overrideprotected void onProgressUpdate(Integer... values) {AsyTest.this.show.setText("更新的資料:  " + Math.random() * 100);}@Overrideprotected String doInBackground(Integer... params) {try {while (true) {Thread.sleep(params[0]);this.publishProgress(100);}} catch (Exception e) {}return null;}}}

  

---恢複內容結束---

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.