MainActivity如下:
package com.example.asynctasktest;import java.io.ByteArrayOutputStream;import java.io.InputStream;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {private Button satrtButton;private Button cancelButton;private ProgressBar progressBar;private TextView textView;private DownLoaderAsyncTask downLoaderAsyncTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initView(); }public void initView() {satrtButton=(Button) findViewById(R.id.startButton);cancelButton=(Button) findViewById(R.id.cancelButton);satrtButton.setOnClickListener(new ButtonOnClickListener());cancelButton.setOnClickListener(new ButtonOnClickListener());progressBar=(ProgressBar) findViewById(R.id.progressBar);textView=(TextView) findViewById(R.id.textView);} private class ButtonOnClickListener implements OnClickListener{public void onClick(View v) {switch (v.getId()) {case R.id.startButton://注意://1 每次需new一個執行個體,建立的任務只能執行一次,否則會出現異常//2 非同步任務的執行個體必須在UI線程中建立//3 execute()方法必須在UI線程中調用。downLoaderAsyncTask=new DownLoaderAsyncTask();downLoaderAsyncTask.execute("http://www.baidu.com");break;case R.id.cancelButton://取消一個正在執行的任務,onCancelled()方法將會被調用 downLoaderAsyncTask.cancel(true);break;default:break;}} } //建構函式AsyncTask<Params, Progress, Result>參數說明: //Params 啟動任務執行的輸入參數 //Progress 背景工作執行的進度 //Result 後台計算結果的類型 private class DownLoaderAsyncTask extends AsyncTask<String, Integer, String>{//onPreExecute()方法用於在執行非同步任務前,主線程做一些準備工作 @Overrideprotected void onPreExecute() {super.onPreExecute();textView.setText("調用onPreExecute()方法--->準備開始執行非同步任務");System.out.println("調用onPreExecute()方法--->準備開始執行非同步任務");}//doInBackground()方法用於在執行非同步任務,不可以更改主線程中UI @Overrideprotected String doInBackground(String... params) { System.out.println("調用doInBackground()方法--->開始執行非同步任務");try {HttpClient client = new DefaultHttpClient();HttpGet get = new HttpGet(params[0]);HttpResponse response = client.execute(get);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {HttpEntity entity = response.getEntity();InputStream is = entity.getContent();long total = entity.getContentLength();ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int count = 0;int length = -1;while ((length = is.read(buffer)) != -1) {bos.write(buffer, 0, length);count += length;//publishProgress()為AsyncTask類中的方法//常在doInBackground()中調用此方法//用於通知主線程,背景工作的執行情況.//此時會觸發AsyncTask中的onProgressUpdate()方法publishProgress((int) ((count / (float) total) * 100));//為了示範進度,休眠1000毫秒Thread.sleep(1000);}return new String(bos.toByteArray(), "UTF-8");}} catch (Exception e) {return null;}return null;}//onPostExecute()方法用於非同步任務執行完成後,在主線程中執行的操作@Overrideprotected void onPostExecute(String result) {super.onPostExecute(result);Toast.makeText(getApplicationContext(), "調用onPostExecute()方法--->非同步任務執行完畢", 0).show();//textView顯示網路請求結果textView.setText(result);System.out.println("調用onPostExecute()方法--->非同步任務執行完畢");} //onProgressUpdate()方法用於更新非同步執行中,在主線程中處理非同步任務的執行資訊 @Overrideprotected void onProgressUpdate(Integer... values) {super.onProgressUpdate(values);//更改進度條progressBar.setProgress(values[0]);//更改TextViewtextView.setText("已經載入"+values[0]+"%");}//onCancelled()方法用於非同步任務被取消時,在主線程中執行相關的操作 @Overrideprotected void onCancelled() {super.onCancelled();//更改進度條進度為0progressBar.setProgress(0);//更改TextViewtextView.setText("調用onCancelled()方法--->非同步任務被取消");System.out.println("調用onCancelled()方法--->非同步任務被取消");} }}
main.xml如下:
<LinearLayout 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" android:orientation="vertical" > <Button android:id="@+id/startButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="開始非同步任務" /> <Button android:id="@+id/cancelButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="取消非同步任務" /> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:max="100" android:progress="0" /> <ScrollView android:id="@+id/scrollView" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="test test" /> </ScrollView></LinearLayout>
重要參考資料:
http://blog.csdn.net/liuhe688/article/details/6532519
Thank you very much