现在的位置: 首页 > 综合 > 正文

httpClient及android 原生接口实现下载并显示图片

2017年10月14日 ⁄ 综合 ⁄ 共 5996字 ⁄ 字号 评论关闭

前言:这篇文章用到了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机制,具体的我也还没弄清楚,分享两个网址:

http://linluan55.blog.163.com/blog/static/175542399201110153463382/

http://www.cnblogs.com/dawei/archive/2011/04/09/2010259.html 

(源码见最底部)

二、使用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;
		}
	}

}

源码来啦,这两个例子的源码我都放在一起了,

源码地址:http://download.csdn.net/detail/harvic880925/6777015(不要分,仅供分享)

 

请大家尊重原创都版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/17609771

抱歉!评论已关闭.