說到異步加載,就會想到Thread,AsyncTask;
說到連接網絡,可以使用HttpURLConnection,HttpClick
不多說什麼,直接在代碼中講解吧。
1,先創建一個網絡連接工具類HttpUtil,裏面有兩個方法,一個使用HttpURLConnection網絡連接獲取圖片,另外一個使用HttpClick連接網絡獲取圖片。
(1)使用:HttpURLConnection
public static Bitmap getHttpURLConnectionBitmap(String address) {
Bitmap bitmap;
InputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
URL url=new URL(address);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
inputStream=connection.getInputStream();
bufferedInputStream=new BufferedInputStream(inputStream);
bitmap= BitmapFactory.decodeStream(bufferedInputStream);
connection.disconnect();//關閉
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedInputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
(2)使用HttpClick:
public static Bitmap getHttpClickBitmap(String address) throws IOException {
HttpClient httpClient =new DefaultHttpClient();
HttpGet httpGet=new HttpGet(address);//Get 請求
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode()==200) {
//請求成功
HttpEntity entity = httpResponse.getEntity();
byte[] data = new byte[1024];
data = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
2,上面已經把網絡獲取圖片工具類寫好了,現在就在MainActivity類中寫異步加載網絡圖片,因爲加載網絡圖片時更新UI是不能在主線程操作的,所以我們開闢一個線程Thread或創建一個類繼承AsyncTask。
(1)在MainActivity裏面寫一個showImageViewbyThread(String url)方法,更新UI的是一張圖片,返回類型是Bitmap。
public Handler mHandel=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bitmap bitmap= (Bitmap) msg.obj;
//更新UI
mImageView.setImageBitmap(bitmap);
}
}
};
/*
*url 圖片的地址
*/
public Bitmap showImageViewbyThread(String url){
//線程
new Thread(){
@Override
public void run() {
super.run();
//通過網絡獲取圖片
Bitmap bitmap=getHttpURLConnectionBitmap(url);
Message message=Message.obtain();
message.obj=bitmap;
//通過handle發送消息
mHandel.sendMessage(message);
}
}.start();
}
(2)使用AsyncTack:在activity新建一個內部類繼承AsyncTack,重寫裏面的父類的方法
/*
*String 圖片的URL地址
*Bitmap 返回一張圖片
*/
class HttpImageAsyncTack extends AsyncTack<String,Void,Bitmap>{
/*
後臺線程操作
*/
@Override
protected Bitmap doInBackground(String... params) {
String param=params[0];
Bitmap bitmap=null;
try {
bitmap=HttpUtil.getHttpClickBitmap(param);
return bitmap;
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
/*
改變UI
*/
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
//顯示圖片
mImageView.setImageBitmap(bitmap);
}
}
3,最後就在activity的onCreate()方法裏面調用
如果使用第2(1)Thread的話
showImageViewbyThread(url);
如果使用2(2)AsyncTack的話
new HttpImageAsyncTack ().execute(url);
今天暫時更時到這裏。