Android开发:AsyncTask异步操作


AsyncTask能够适当地、简单地用于 UI线程。这个类准许执行后台操作,让那些没有熟练操作线程的操作者在 UI线程上发布结果。

异步任务的定义是一个在后台线程上运行,其结果是在 UI线程上发表的计算。、

异步任务被定义成三种一般类型: Params, Progress和 Result;

四步: begin , doInBackground , processProgress和end.

自己写的练习

  1. import Android.app.Activity;   
  2. import android.os.AsyncTask;   
  3. import android.os.Bundle;   
  4. import android.util.Log;  
  5.   
  6.   protected void onCreate(Bundle savedInstanceState) {   
  7.     super .onCreate(savedInstanceState);   
  8.     setContentView(R.layout.main);    
  9.     //AsyncTask.execute()要在主线程里调用 ,新建了一堆线程,写这么多是为了便于查看效果   
  10.     new AsyncLoader().execute("aaaa");  
  11.     new AsyncLoader().execute("bbbb");  
  12.     new AsyncLoader().execute("cccc");  
  13.     new AsyncLoader().execute("dddd");  
  14.     new AsyncLoader().execute("eeee");  
  15.     new AsyncLoader().execute("ffff");  
  16.   }  
  17.   
  18.   
  19.   //AsyncTask    
  20.   class AsyncLoader extends AsyncTask<String, Integer, Integer>{  
  21.   
  22.   
  23.     @Override  
  24.     protected Integer doInBackground(String... arg0) {  
  25.           
  26.         Log.i("AsyncLoader""doInBackground:"+arg0[0]);  
  27.         for (int i = 0; i < 2; i++) {  
  28.             publishProgress(i);//发送更新进度消息   
  29.             try {   
  30.                   Thread.sleep(1000);   
  31.                 } catch (InterruptedException e) {   
  32.                   e.printStackTrace();   
  33.                 }   
  34.         }  
  35.         return 0;  
  36.     }  
  37.   
  38.   
  39.     @Override  
  40.     protected void onCancelled() {  
  41.         Log.i("AsyncLoader""onCancelled");  
  42.         super.onCancelled();  
  43.     }  
  44.   
  45.   
  46.     @Override  
  47.     protected void onPostExecute(Integer result) {  
  48.         Log.i("AsyncLoader""onPostExecute:result="+result);  
  49.         super.onPostExecute(result);  
  50.     }  
  51.   
  52.   
  53.     @Override  
  54.     protected void onProgressUpdate(Integer... values) {  
  55.         //打印进度   
  56.         Log.i("AsyncLoader""progress:"+ values[0]);  
  57.         super.onProgressUpdate(values);  
  58.     }   
  59.   }   
  60. }  

相关内容