1. 程式人生 > >httpClient及android 原生介面實現下載並顯示圖片

httpClient及android 原生介面實現下載並顯示圖片

前言:這篇文章用到了Android的handler機制,對於handler機制我也還沒搞得太清楚,只能先把相關的幾個帖子貼上,大家先看看吧,等後面理解了再仔細講講,最後我另外給出了用android原生HttpURLConnection是怎樣來下載並顯示圖片的,但這種方法一般不用,所以我也就不講了,如果想看就看原始碼吧

上效果圖:

    

配置AndroidManifest.xml

新增網際網路訪問許可權

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 

XML程式碼:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnFirst"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="非同步下載方式一" >
    </Button>

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="fill_parent"
        android:layout_height="match_parent" >
		<!-- 用於顯示載入的圖片 -->
        <ImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="2dp"
            android:scaleType="centerInside" >
        </ImageView>

        <ProgressBar
            android:id="@+id/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:layout_gravity="center" >
        </ProgressBar>
    </FrameLayout>
</LinearLayout>

一、使用httpClient實現下載圖片

android程式碼: 

/**
 * @author harvic
 * @date 2013-12-27
 * 
 */
package com.example.try_downloadimage_httpclient;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

	//伺服器上的圖片地址
	private static final String picURL="http://222.195.151.19/1.jpg";
	
	private Button btnFirst;
	private FrameLayout frameLayout;
	private Bitmap bitmap=null;
	private ProgressBar progress;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		 btnFirst=(Button)this.findViewById(R.id.btnFirst);
		 frameLayout=(FrameLayout)this.findViewById(R.id.frameLayout);
		 progress=(ProgressBar)this.findViewById(R.id.progress);
		 btnFirst.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				progress.setVisibility(View.VISIBLE);//顯示PrograssBar
				
				// 啟動一個後臺執行緒
				handler.post(new Runnable() {
					@Override
					public void run() {
						DefaultHttpClient httpclient = new DefaultHttpClient();
						
						HttpGet httpget = new HttpGet(picURL);

						try {
							HttpResponse resp = httpclient.execute(httpget);
							//判斷是否正確執行
							if (HttpStatus.SC_OK == resp.getStatusLine().getStatusCode()) {
								//將返回內容轉換為bitmap
								HttpEntity entity = resp.getEntity();
								InputStream in = entity.getContent();
								bitmap = BitmapFactory.decodeStream(in);
								
								//向handler傳送訊息,執行顯示圖片操作
								Message msg = new Message();
								msg.what = 1;
								handler.sendMessage(msg);
							}

						} catch (Exception e) {
							e.printStackTrace();
							setTitle(e.getMessage());
						} finally {
							httpclient.getConnectionManager().shutdown();
						}
					}
				});
				
			}
		});
	}

	/** 這裡重寫handleMessage方法,接受到子執行緒資料後更新UI **/
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// 關閉
				ImageView view = (ImageView) frameLayout
						.findViewById(R.id.image);
				view.setImageBitmap(bitmap);
				progress.setVisibility(View.INVISIBLE);//隱藏PrograssBar

				break;
			}
		}
	};

}

注意:

1、這裡用的是本地伺服器,也就是我的電腦,所以你要把IP地址改成你自己的IP地址;

 2、這裡用到了handler機制,具體的我也還沒弄清楚,分享兩個網址:

(原始碼見最底部)

二、使用android原生介面實現

 效果圖:

 

 1、XML與上例相同

 2、android程式碼

package com.example.try_asyncloadimage_1;
/**
 * 完成下載圖片功能
 * 
 */

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class MainActivity extends Activity implements OnClickListener{
	private static final String picURL="http://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Hukou_Waterfall.jpg/800px-Hukou_Waterfall.jpg";
//	private static final String picURL="http://222.195.151.19/1.jpg";
	
	private Button btnFirst;
	private ProgressBar progress;
	private FrameLayout frameLayout;
	private Bitmap bitmap=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		 btnFirst=(Button)this.findViewById(R.id.btnFirst);
		 progress=(ProgressBar)this.findViewById(R.id.progress);
		 progress.setVisibility(View.GONE);
		 frameLayout=(FrameLayout)this.findViewById(R.id.frameLayout);

		 btnFirst.setOnClickListener(this);
	}

	/** 這裡重寫handleMessage方法,接受到子執行緒資料後更新UI **/
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// 關閉
				ImageView view = (ImageView) frameLayout
						.findViewById(R.id.image);
				view.setImageBitmap(bitmap);
				break;
			}
		}
	};

	// 前臺ui執行緒在顯示ProgressDialog,
	// 後臺執行緒在下載資料,資料下載完畢,關閉進度框
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btnFirst:
			// 啟動一個後臺執行緒
			handler.post(new Runnable() {
				@Override
				public void run() {
					// 這裡下載資料
					try {
						URL url = new URL(picURL);
						HttpURLConnection conn = (HttpURLConnection) url
								.openConnection();
						conn.setDoInput(true);
						conn.connect();
						InputStream inputStream = conn.getInputStream();
						bitmap = BitmapFactory.decodeStream(inputStream);
						Message msg = new Message();
						msg.what = 1;
						handler.sendMessage(msg);

					} catch (MalformedURLException e1) {
						e1.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			});
			break;
		}
	}

}

原始碼來啦,這兩個例子的原始碼我都放在一起了,