Android中AsyncTask使用實例
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()方法用于在執行異步任務前,主線程做一些準備工作 @Override protected void onPreExecute() { super.onPreExecute(); textView.setText("調用onPreExecute()方法--->準備開始執行異步任務"); System.out.println("調用onPreExecute()方法--->準備開始執行異步任務"); } //doInBackground()方法用于在執行異步任務,不可以更改主線程中UI @Override protected 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()方法用于異步任務執行完成后,在主線程中執行的操作 @Override protected void onPostExecute(String result) { super.onPostExecute(result); Toast.makeText(getApplicationContext(), "調用onPostExecute()方法--->異步任務執行完畢", 0).show(); //textView顯示網絡請求結果 textView.setText(result); System.out.println("調用onPostExecute()方法--->異步任務執行完畢"); } //onProgressUpdate()方法用于更新異步執行中,在主線程中處理異步任務的執行信息 @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); //更改進度條 progressBar.setProgress(values[0]); //更改TextView textView.setText("已經加載"+values[0]+"%"); } //onCancelled()方法用于異步任務被取消時,在主線程中執行相關的操作 @Override protected void onCancelled() { super.onCancelled(); //更改進度條進度為0 progressBar.setProgress(0); //更改TextView textView.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>
本文由用戶 engd 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!