Android異步任務執行AsyncTask使用介紹

jopen 12年前發布 | 38K 次閱讀 Android Android開發 移動開發

android的主線程也就是UI線程不允許耗時的操作。否則會引起Answer Not Responding(ARN)異常。所以有兩種機制用來處理耗時的操作。一種就是前面所提到的利用Handler來處理耗時的任務,還有一種就是本文介紹的一步任務處理機制:AsyncTask。所謂的異步任務機制就是UI線程符合和用戶來進行流暢的交互而一些耗時的操作留給后臺線程來完成。

public abstract class  AsyncTask extends Object。AsyncTask是一個抽象類。所以想利用異步任務機制來處理時必須要繼承抽象類并實現類里面的抽象方法并根據需求重寫類里面的方法。操作過程中一般重寫它如下的幾個方法:

onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

onPreExecute():在任務被執行以前有UI主線程來調用這個函數來實現一些初始化的操作,例如在用戶界面上顯示一個進度條。

doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step。

doInBackGround(Params...)在onPreExecute()被調用之后由后臺進程來調用這個函數來繼續任務的操作。Params作為參數被傳遞給任務。計算的結果必須返回給最后一步操作。在這里同樣可以調用publishProgress(progress...)來打印若干個進度條。在 OnProgressUpdate(Progress...)中,這些返回值就是這里 的參數progress,用來顯示進度值。

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field。

該函數由publishProgress(Progress...)調用來顯示進度。

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter。

當后臺計算完成時由UI主線程調用。

當然,當我們自定義的類雖然已經繼承了AsyncTask之后,我們如何來啟動這個任務呢。看看對象執行調用的一些方法:

首先必須在主線程UI中創建該類的實例對象,并調用該對象的execute()方法。這樣android就會自動調用這些重寫的函數了。注意:該異步任務只能被execute一次,否則會拋出異常。

熟悉了這幾個函數之后我們看看下面的一個例子:

public class MainActivity extends Activity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView=(TextView)findViewById(R.id.textview);
    }

    public void downLoad(View source)throws MalformedURLException{
        DownTask task=new DownTask(this);
        task.execute(10);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    class DownTask extends AsyncTask<Integer,Integer,String>{
        Context mContext;
        ProgressDialog pDialog;
        int count=0;
        public DownTask(Context ctx)
        {
            mContext=ctx;
        }
        @Override
        protected String doInBackground(Integer... params) {
            try{
            for(int i=0;i<100;i++)
            {   Thread.sleep(500);
                count++;
                publishProgress(count);
            }}catch(Exception e)
            {
                Log.v("Exception", e.getMessage());
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(mContext, "completed", Toast.LENGTH_LONG).show();
            pDialog.dismiss();

        }
        @Override
        protected void onPreExecute() {
            pDialog=new ProgressDialog(mContext);
            pDialog.setMax(100);
            pDialog.setTitle("下載中......");
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setIndeterminate(false);
            pDialog.show();

        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            pDialog.setProgress(values[0]);
        }

}
}

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!