AsyncTask也叫做“異步任務(wù)”,是一個(gè)抽象類
AsyncTask約定了在子線程中執(zhí)行任務(wù)的抽象方法,開(kāi)發(fā)者可以在自定義AsyncTask的實(shí)現(xiàn)類中重寫(xiě)該方法,
則AsyncTask在工作時(shí)會(huì)自動(dòng)開(kāi)啟子線程執(zhí)行相關(guān)代碼
AsyncTask類的聲明:
public abstract class AsyncTask<Param,Progress,Result>
Param 執(zhí)行異步任務(wù)后,需要參數(shù)的數(shù)據(jù)類型
Progress 執(zhí)行異步任務(wù)過(guò)程中,標(biāo)識(shí)進(jìn)度的數(shù)據(jù)類型
Result 執(zhí)行異步任務(wù)后,需要返回的結(jié)果的數(shù)據(jù)類型
AsyncTask中的抽象方法: public abstract Result doInBackground(params... params)
讓AsyncTask開(kāi)始工作:
public final AsyncTask<params,Progress,Result> execute(params...params)
該方法被調(diào)用后,會(huì)自動(dòng)開(kāi)啟子線程并調(diào)用dnInBackground()方法,該方法必須在UI線程中調(diào)用
案例:
布局:
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="104dp" android:onClick="doAsyncTask" android:text="開(kāi)始" />
MainActivity:
 public class MainActivity extends Activity {   @Override   protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     System.out.println("onCreate" + Thread.currentThread().getId());   }   public void doAsyncTask(View view){     new InnerAsyncTask().execute("");   }   private class InnerAsyncTask extends AsyncTask<Object, Object, Object>{     @Override     protected Object doInBackground(Object... params) {       for(int i = 0; i < 30;i++){         System.out.println("InnerAsyncTask" + Thread.currentThread().getId());         try {           Thread.sleep(1000);         } catch (InterruptedException e) {           e.printStackTrace();         }       }       return null;     }   } } AsyncTask更新UI
AsyncTask約定了任務(wù)執(zhí)行完畢后的回調(diào)方法,該方法并不是抽象的,開(kāi)發(fā)者可以選擇性的實(shí)現(xiàn)。
protected void onPostExecute(Result result)
該方法是運(yùn)行在主線程的方法
實(shí)例:
布局:
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="104dp" android:onClick="doAsyncTask" android:text="開(kāi)始" /> <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/button1" android:layout_centerHorizontal="true" android:layout_marginTop="22dp" android:src="@drawable/abs" />
MainActivity:
 public class MainActivity extends Activity {   private ImageView image;   @Override   protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);      image = (ImageView) findViewById(R.id.imageView1);  //   System.out.println("onCreate" + Thread.currentThread().getId());   }   public void doAsyncTask(View view){     new InnerAsyncTask().execute("");   }   private class InnerAsyncTask extends AsyncTask<String,Integer, Bitmap>{     @Override     protected Bitmap doInBackground(String... params) {       try {         Thread.sleep(3000);       } catch (InterruptedException e) {         // TODO Auto-generated catch block         e.printStackTrace();       }       return BitmapFactory.decodeResource(getResources(), R.drawable.abc);     }      @Override     protected void onPostExecute(Bitmap result) {       image.setImageBitmap(result);         }   } } AsyncTask更新進(jìn)度
AsyncTask約定了任務(wù)執(zhí)行過(guò)程中,更新進(jìn)度的回調(diào)方法,該方法并不是抽象的,開(kāi)發(fā)者可以選擇性地實(shí)現(xiàn)。
protected void onProgressUpdate(Progress... values)(該方法運(yùn)行在主線程)
在任務(wù)執(zhí)行過(guò)程中,可以調(diào)用publishProgress()方法提交進(jìn)度,使得onProgressUpdate()方法被回調(diào)
實(shí)例
布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/tv_pb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="100%" android:visibility="gone" android:textSize="16sp"/> <Button android:id="@+id/btn_update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="104dp" android:onClick="doAsyncTask" android:text="開(kāi)始" /> <ImageView android:id="@+id/iv_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/btn_update" android:layout_centerHorizontal="true" android:layout_marginTop="22dp" android:src="@drawable/abs" /> <ProgressBar android:id="@+id/pb_progress" style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:max="100" android:visibility="gone" android:layout_alignRight="@+id/btn_update" android:layout_marginTop="32dp" /> </RelativeLayout>
LoadImage:
public class LoadImage extends AsyncTask<String, Integer, Object> {   private Context context;   private ImageView imageview;   private Bitmap image;   private Button button;   private ProgressBar pg;   private TextView tv;   public LoadImage(Context context, Button button, ImageView imageview,       ProgressBar pg, TextView tv) {     this.context = context;     this.imageview = imageview;     this.button = button;     this.pg = pg;     this.tv = tv;   }   @Override   protected Object doInBackground(String... params) {     for (int i = 0; i <= 100; i++) {       publishProgress(i);     try {       Thread.sleep(50);     } catch (InterruptedException e) {       // TODO Auto-generated catch block       e.printStackTrace();     }     }     image = BitmapFactory.decodeResource(context.getResources(),         R.drawable.abc);     return null;   }   @Override   protected void onProgressUpdate(Integer... values) {     // TODO Auto-generated method stub     pg.setProgress(values[0]);     tv.setText(values[0] + "%");   }   @Override   protected void onPostExecute(Object result) {     imageview.setImageBitmap(image);     button.setEnabled(true);     pg.setVisibility(View.GONE);     tv.setVisibility(View.GONE);   } } MainActivity:
 public class MainActivity extends Activity {   private ImageView image;   private Button button;   private ProgressBar pg;   private TextView tv;    @Override   protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);      image = (ImageView) findViewById(R.id.iv_image);        button = (Button) findViewById(R.id.btn_update);      pg = (ProgressBar) findViewById(R.id.pb_progress);      tv = (TextView) findViewById(R.id.tv_pb);   }   public void doAsyncTask(View view){     button.setEnabled(false);     pg.setVisibility(View.VISIBLE);     tv.setVisibility(View.VISIBLE);     new LoadImage(this,button,image,pg,tv).execute("");   } } AsyncTask是一個(gè)綜合了任務(wù)的執(zhí)行、進(jìn)度更新、結(jié)果提交的類,使用AsyncTask
可以集中的編寫(xiě)某個(gè)異步任務(wù)的全部代碼,而不必關(guān)心線程間的通信問(wèn)題,降低了
編碼出錯(cuò)幾率,并有效的提高了代碼的可閱讀性、可維護(hù)性等。
小案例之異步加載圖片
使用到的技術(shù): Canvas(畫(huà)布)、Paint(畫(huà)筆)
Canvas(畫(huà)布):用來(lái)決定畫(huà)布的基礎(chǔ)屬性,執(zhí)行繪制
Paint(畫(huà)筆):設(shè)置顏色、設(shè)置字體、其他的設(shè)置
同一次繪圖過(guò)程中,可能需要多個(gè)畫(huà)筆對(duì)象,或多次調(diào)整畫(huà)筆的屬性
使用Canvas:
	public Canvas()
	public Canvas(Bitmap bitmap)
	public void drawRect(float left,float top,float right,float bottom,Paint paint)
	public void drawBitmap(Bitmap bitmap,float left,float top,Paint paint)
	public void drawText(String text,float x,float y,Paint paint)
使用Paint:
	public Paint()
	public native void setColr(int color)
	public native void setAntiAlias(boolean aa)
	public native void setTextSize(float textSize)
	public void setTextAlign(Align align)
	public Xfermode setXfermode(Xfermode xfermode)
總結(jié)
以上就是本文關(guān)于AsyncTask類實(shí)例詳解的全部?jī)?nèi)容,希望對(duì)大家有所幫助。有什么問(wèn)題可以隨時(shí)留言,歡迎大家交流討論。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注