線程在安卓開發中非常重要,很大程度上決定安卓app的性能。不會阻礙主線程的操作,並且會把結果發佈在主線程上。在android3.0版本以上,不允許主線程直接訪問網絡,爲了讓UI在展示的過程中比較流暢。需要開啓新的子線程去完成下載等耗時任務的操作,並把下載結果更新到UI上。AsyncTask(異步任務)是一個線程框架,封裝了Thread和Handler,異步任務用於短時間的耗時操作,如果是長時間的耗時操作的話要用線程池。
整體思路:在xml文件中放入一個Button控件和一個ImageView控件,在activity中 聲明一個異步任務,使用異步任務的規則:1.聲明一個類繼承AsyncTask 標註三個參數的類型,2.第一個參數表示要執行的任務通常是網絡的路徑,第二個參數表示進度的刻度,第三個參數表示任務執行的返回結果類型,重寫三個方法onPreExecute、doInBackground、onPostExecute,這三個方法分別表示任務執行之前的操作、完成耗時操作、更新UI操作,在onPreExecute方法中展示定義的dialog對象,在doInBackground方法中,通過一個網址來獲取網絡圖片,並返回一個bitmap類型的圖片對象,在onPostExecute這個方法中,將獲取的圖片綁定到ImageView控件上,並將dialog對象消失。在activity的onCreate方法中執行異步任務操作,並傳遞一個獲取圖片的網址。注意在清單文件AndroidManifest.xml中添加連接網絡的授權。
activity_main.xml文件:
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="下載網絡圖片" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
MainActivity.java文件:
package com.example.android_asynctask_download;
//使用異步任務圓形滾動條下載圖片並顯示
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.renderscript.Program;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private Button button;
private ImageView imageView;
private String image_path="http://pica.nipic.com/2007-11-09/200711912453162_2.jpg";
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
imageView=(ImageView)findViewById(R.id.imageView1);
dialog=new ProgressDialog(this);
dialog.setTitle("提示信息");
dialog.setMessage("正在下載,請稍候...");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 執行異步任務的操作
new MyTask().execute(image_path);
/*
// new Thread(new Runnable() {
//
// @Override
// public void run() {
// // TODO Auto-generated method stub
// 在UI的主線程中,不能直接訪問網絡
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(image_path);
try {
httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
// }).start();
*/
}
});
}
// 聲明一個異步任務 void表示是沒有類型的
// 使用異步任務的規則:
// 1.聲明一個類繼承AsyncTask 標註三個參數的類型
// 2.第一個參數表示要執行的任務通常是網絡的路徑,第二個參數表示進度的刻度
// 第三個參數表示任務執行的返回結果類型
public class MyTask extends AsyncTask<String, Void, Bitmap>{
// 表示任務執行之前的操作
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.show();
}
// 主要是完成耗時操作
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
// 使用網絡鏈接類HttpClient類完成對網絡數據的提取
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(params[0]);
Bitmap bitmap=null;
try {
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity=httpResponse.getEntity();
// 把一個實體類轉化成一個字節數組
byte[] data=EntityUtils.toByteArray(httpEntity);
bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
// 主要是更新UI操作
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
imageView.setImageBitmap(result);
dialog.dismiss();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}