您好,登錄后才能下訂單哦!
AsyncTask是Android解決異步加載的一種方案,它比Handler和Message的方式更加輕量級(jí)。
一般的使用步驟:
自定義一個(gè)繼承AsyncTask的類。自定義時(shí)可以傳入AsyncTask的3個(gè)泛型參數(shù),即Params,Progress和Result。Params是需要傳入的參數(shù),Progress是進(jìn)程執(zhí)行的百分比,Result是最終返回的結(jié)果。
實(shí)現(xiàn)從AsyncTask繼承下來(lái)的方法。
主要有onPreExecute()、doInBackground(Params...)、onProgressUpdate(Progress...)和onPostExecute(Result)四種方法。
其中,
onPreExecute():執(zhí)行實(shí)際后臺(tái)操作之前被調(diào)用。
doInBackground(Params...):緊跟onPreExecute()之后進(jìn)行的實(shí)際后臺(tái)操作,一般進(jìn)行比較耗時(shí) 的操作,更新實(shí)時(shí)任務(wù)進(jìn)度,可以調(diào)用publishProgress()。
onProgressUpdate(Progress...):運(yùn)行與UI線程,可更新實(shí)時(shí)進(jìn)度。
onPostExecute(Result):運(yùn)行于UI線程,其參數(shù)就是doInBackground()的返回值。
3.在主線程中創(chuàng)建AsyncTask對(duì)象,并調(diào)用execute()方法。
具體示例來(lái)展示AsyncTask異步加載:
MainActivity代碼:
public class MainActivity extends Activity {
private TextView textview;
private Button button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=(TextView)findViewById(R.id.text);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
LoadTask task=new LoadTask();
task.execute();
}
});
}
private class LoadTask extends AsyncTask<Void,Integer,String>{
private ProgressDialog progressdialog;
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
int sum=1;
while(sum<=10){
try {
Thread.sleep(1000);
publishProgress(sum);
sum++;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "加載完成。";
}
//緊跟onPreExecute()之后緊跟的操作,進(jìn)行耗時(shí)操作,利用publishprogress()更新。
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressdialog=progressdialog.show(MainActivity.this, "AsyncTask Demo", "載入中...",true);
}
//在doinbackground之前調(diào)用,創(chuàng)建一個(gè)對(duì)話框。
protected void onProgressUpdate(Integer...values){
textview.setText(values[0]*10+"%");
}
//運(yùn)行于ui線程,更新實(shí)時(shí)進(jìn)度。
protected void onPostExecute(String result){
progressdialog.dismiss();
textview.setText(result);
}
//運(yùn)行于ui線程,返回值就是doInBackground()的返回值。
}
}
xml代碼:
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="--" />
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/text"
android:layout_marginTop="24dp"
android:text="開始載入" />
點(diǎn)擊按鈕,即可實(shí)現(xiàn)異步加載。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。