AsyncTask類實例詳解
AsyncTask也叫做“異步任務”,是一個抽象類
AsyncTask約定了在子線程中執(zhí)行任務的抽象方法,開發(fā)者可以在自定義AsyncTask的實現類中重寫該方法,
則AsyncTask在工作時會自動開啟子線程執(zhí)行相關代碼
AsyncTask類的聲明:
public abstract class AsyncTask<Param,Progress,Result>
Param 執(zhí)行異步任務后,需要參數的數據類型
Progress 執(zhí)行異步任務過程中,標識進度的數據類型
Result 執(zhí)行異步任務后,需要返回的結果的數據類型
AsyncTask中的抽象方法: public abstract Result doInBackground(params... params)
讓AsyncTask開始工作:
public final AsyncTask<params,Progress,Result> execute(params...params)
該方法被調用后,會自動開啟子線程并調用dnInBackground()方法,該方法必須在UI線程中調用
案例:
布局:
<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="開始" />
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約定了任務執(zhí)行完畢后的回調方法,該方法并不是抽象的,開發(fā)者可以選擇性的實現。
protected void onPostExecute(Result result)
該方法是運行在主線程的方法
實例:
布局:
<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="開始" /> <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更新進度
AsyncTask約定了任務執(zhí)行過程中,更新進度的回調方法,該方法并不是抽象的,開發(fā)者可以選擇性地實現。
protected void onProgressUpdate(Progress... values)(該方法運行在主線程)
在任務執(zhí)行過程中,可以調用publishProgress()方法提交進度,使得onProgressUpdate()方法被回調
實例
布局:
<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="開始" />
<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是一個綜合了任務的執(zhí)行、進度更新、結果提交的類,使用AsyncTask
可以集中的編寫某個異步任務的全部代碼,而不必關心線程間的通信問題,降低了
編碼出錯幾率,并有效的提高了代碼的可閱讀性、可維護性等。
小案例之異步加載圖片
使用到的技術: Canvas(畫布)、Paint(畫筆)
Canvas(畫布):用來決定畫布的基礎屬性,執(zhí)行繪制
Paint(畫筆):設置顏色、設置字體、其他的設置
同一次繪圖過程中,可能需要多個畫筆對象,或多次調整畫筆的屬性
使用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)
總結
以上就是本文關于AsyncTask類實例詳解的全部內容,希望對大家有所幫助。歡迎參閱本站:Android開發(fā)實現文件關聯方法介紹、Android分包MultiDex策略詳解等,有什么問題可以隨時留言,歡迎大家交流討論。
相關文章
Android Zipalign工具優(yōu)化Android APK應用
本文主要介紹Android Zipalign工具優(yōu)化Android APK應用,這里整理了相關資料及簡單優(yōu)化實例,有需要的小伙伴可以參考下2016-09-09
Android中自定義View實現圓環(huán)等待及相關的音量調節(jié)效果
這篇文章主要介紹了Android中自定義View實現圓環(huán)等待及相關的音量調節(jié)效果,邏輯非常簡單,或許繪圖方面更加繁瑣XD 需要的朋友可以參考下2016-04-04
簡略分析Android的Retrofit應用開發(fā)框架源碼
這篇文章主要介紹了Android的Retrofit應用開發(fā)框架的源碼分析,作者對Volley和Retrofit兩個框架進行了一些對比,比較精彩,需要的朋友可以參考下2016-02-02
Android Studio開發(fā)環(huán)境搭建教程詳解
android studio是最近比較火的開發(fā),那么android studio開發(fā)環(huán)境怎么搭建呢?下面通過本文給大家記錄下Android Studio開發(fā)環(huán)境搭建教程詳解,需要的朋友參考下吧2017-11-11

