android AsyncTask執行個體,androidasynctask
.java
1 package com.example.activitydemoay; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.AsyncTask; 6 import android.os.Bundle; 7 import android.view.View; 8 import android.widget.Button; 9 import android.widget.ProgressBar;10 import android.widget.TextView;11 12 public class MainActivity extends Activity {13 14 Button download;15 ProgressBar pb;16 TextView tv;17 18 @Override19 protected void onCreate(Bundle savedInstanceState) {20 super.onCreate(savedInstanceState);21 setContentView(R.layout.activity_main);22 23 pb = (ProgressBar) findViewById(R.id.pb);24 tv = (TextView) findViewById(R.id.tv);25 26 download = (Button) findViewById(R.id.download);27 download.setOnClickListener(new View.OnClickListener() {28 @Override29 public void onClick(View v) {30 DownloadTask dTask = new DownloadTask();31 dTask.execute(100);32 }33 });34 }35 36 class DownloadTask extends AsyncTask<Integer, Integer, String> {37 // 後面角括弧內分別是參數(例子裡是線程休息時間),進度(publishProgress用到),傳回值 類型38 39 @Override40 protected void onPreExecute() {41 // 第一個執行方法42 super.onPreExecute();43 }44 45 @Override46 protected String doInBackground(Integer... params) {47 // 第二個執行方法,onPreExecute()執行完後執行48 for (int i = 0; i <= 100; i++) {49 pb.setProgress(i);50 publishProgress(i);51 try {52 Thread.sleep(params[0]);53 } catch (InterruptedException e) {54 e.printStackTrace();55 }56 }57 return "執行完畢";58 }59 60 @Override61 protected void onProgressUpdate(Integer... progress) {62 // 這個函數在doInBackground調用publishProgress時觸發,雖然調用時只有一個參數63 // 但是這裡取到的是一個數組,所以要用progesss[0]來取值64 // 第n個參數就用progress[n]來取值65 tv.setText(progress[0] + "%");66 super.onProgressUpdate(progress);67 }68 69 @Override70 protected void onPostExecute(String result) {71 // doInBackground返回時觸發,換句話說,就是doInBackground執行完後觸發72 // 這裡的result就是上面doInBackground執行後的傳回值,所以這裡是"執行完畢"73 setTitle(result);74 Intent intent = new Intent();75 // Intent傳遞參數76 // intent.putExtra("TEST", "123");77 // intent.setClass(MainActivity.this, MainActivityB.class);78 // MainActivity.this.startActivity(intent);79 super.onPostExecute(result);80 }81 82 }83 84 }
.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" 4 android:layout_width="fill_parent" 5 android:layout_height="fill_parent" 6 > 7 <TextView 8 android:layout_width="fill_parent" 9 android:layout_height="wrap_content" 10 android:text="Hello , Welcome to Andy's Blog!"/> 11 <Button 12 android:id="@+id/download" 13 android:layout_width="fill_parent" 14 android:layout_height="wrap_content" 15 android:text="Download"/> 16 <TextView 17 android:id="@+id/tv" 18 android:layout_width="fill_parent" 19 android:layout_height="wrap_content" 20 android:text="當前進度顯示"/> 21 <ProgressBar 22 android:id="@+id/pb" 23 android:layout_width="fill_parent" 24 android:layout_height="wrap_content" 25 >26 </LinearLayout>