AsyncTask類實例詳解
AsyncTask也叫做“異步任務(wù)”,是一個抽象類
AsyncTask約定了在子線程中執(zhí)行任務(wù)的抽象方法,開發(fā)者可以在自定義AsyncTask的實現(xiàn)類中重寫該方法,
則AsyncTask在工作時會自動開啟子線程執(zhí)行相關(guān)代碼
AsyncTask類的聲明:
public abstract class AsyncTask<Param,Progress,Result>
Param 執(zhí)行異步任務(wù)后,需要參數(shù)的數(shù)據(jù)類型
Progress 執(zhí)行異步任務(wù)過程中,標識進度的數(shù)據(jù)類型
Result 執(zhí)行異步任務(wù)后,需要返回的結(jié)果的數(shù)據(jù)類型
AsyncTask中的抽象方法: public abstract Result doInBackground(params... params)
讓AsyncTask開始工作:
public final AsyncTask<params,Progress,Result> execute(params...params)
該方法被調(diào)用后,會自動開啟子線程并調(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="開始" />
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)方法,該方法并不是抽象的,開發(fā)者可以選擇性的實現(xiàn)。
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約定了任務(wù)執(zhí)行過程中,更新進度的回調(diào)方法,該方法并不是抽象的,開發(fā)者可以選擇性地實現(xiàn)。
protected void onProgressUpdate(Progress... values)(該方法運行在主線程)
在任務(wù)執(zhí)行過程中,可以調(diào)用publishProgress()方法提交進度,使得onProgressUpdate()方法被回調(diào)
實例
布局:
<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是一個綜合了任務(wù)的執(zhí)行、進度更新、結(jié)果提交的類,使用AsyncTask
可以集中的編寫某個異步任務(wù)的全部代碼,而不必關(guān)心線程間的通信問題,降低了
編碼出錯幾率,并有效的提高了代碼的可閱讀性、可維護性等。
小案例之異步加載圖片
使用到的技術(shù): Canvas(畫布)、Paint(畫筆)
Canvas(畫布):用來決定畫布的基礎(chǔ)屬性,執(zhí)行繪制
Paint(畫筆):設(shè)置顏色、設(shè)置字體、其他的設(shè)置
同一次繪圖過程中,可能需要多個畫筆對象,或多次調(diào)整畫筆的屬性
使用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類實例詳解的全部內(nèi)容,希望對大家有所幫助。歡迎參閱本站:Android開發(fā)實現(xiàn)文件關(guān)聯(lián)方法介紹、Android分包MultiDex策略詳解等,有什么問題可以隨時留言,歡迎大家交流討論。
相關(guān)文章
android?scrollview頂部漸漸消失實現(xiàn)實例詳解
這篇文章主要為大家介紹了android?scrollview頂部漸漸消失實現(xiàn)實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11
Android Recyclerview實現(xiàn)上拉加載更多功能
在項目中使用列表的下拉刷新和上拉加載更多是很常見的功能。下文給大家?guī)砹薃ndroid Recyclerview上拉加載更多功能,需要的朋友參考下吧2017-05-05
Android實現(xiàn)類似網(wǎng)易新聞選項卡動態(tài)滑動效果
這篇文章主要介紹了Android實現(xiàn)類似網(wǎng)易新聞選項卡動態(tài)滑動效果的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-11-11
Android提高之SQLite分頁表格實現(xiàn)方法
這篇文章主要介紹了Android提高之SQLite分頁表格實現(xiàn)方法,在項目開發(fā)中有很高的實用價值,需要的朋友可以參考下2014-08-08
Android View源碼解讀 DecorView與ViewRootImpl淺談
這篇文章主要解讀了Android View源碼,為大家詳細介紹DecorView與ViewRootImpl,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02
Android開發(fā)之獲取短信驗證碼后按鈕背景變化并且出現(xiàn)倒計時
在開發(fā)是經(jīng)常會遇到獲取短信驗證碼,然后獲取驗證碼后需要等待n秒倒計時,這時是不能再次發(fā)送短信請求的,這是需要一個倒計時程序,本文給大家分享了實現(xiàn)此功能的代碼,需要的朋友參考下2016-01-01

