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

android通过http协议获得图片

2014年01月22日 ⁄ 综合 ⁄ 共 2247字 ⁄ 字号 评论关闭

android通过图片网址获得图片并显示在imageView中。

下面就简单的来说明操作过程:

首先必须在布局文件中声明imageView控件:

 <ImageView
            android:id="@+id/image"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

还必须在清单文件中加入访问网络的权限:

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

其次:用一个service类来实现访问http协议,并且获得链接的返回值这个过程:htmlPath是图片的网络地址

public class PageService {
/**@description:获取图片的数据	
	 * @author:Administrator
	 * @return:byte[]
	 * @param htmlpath
	 * @return
	 * @throws Exception
	 */
	
	public static byte[] getImage(String htmlpath) throws Exception {
		byte[] imagearray = null;
		URL url = new URL(htmlpath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		// conn.setRequestMethod("GET");
		conn.connect();
		if (conn.getResponseCode() == 200) {
			byte[] buffer = new byte[1024];
			ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
			int len = 0;
			InputStream inputStream = conn.getInputStream();
			while ((len = inputStream.read(buffer)) != -1) {
				arrayOutputStream.write(buffer, 0, buffer.length);
			}
			imagearray = arrayOutputStream.toByteArray();
		}
		return imagearray;

	}
}

最后在activity中启用一个线程来调用这个业务方法,并在handler中对UI进行更新:(必须实现线程否则会出错,这是和3.0版本之前不同的地方)

public class MainActivity extends Activity {
	private EditText strpath;
	private TextView htmlcontent;
	private ImageView imageview;
    Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
byte[] data=(byte[])msg.obj;
					Bitmap image=BitmapFactory.decodeByteArray(data, 0, data.length);
					imageview.setImageBitmap(image);}

下面是线程中的内容:

 

private final class ImageThread extends Thread {

	@Override
	public void run() {
		String htmlpath=strpath.getText().toString();
		htmlpath="http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif";
		byte[] htmlarray=null;
		try {
			 htmlarray=PageService.getImage(htmlpath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Message msg=new Message();
		msg.obj=htmlarray;
		msg.what=1;
		handler.sendMessage(msg);
	}
	 
 }

 

最后用点击一个button来触发获取图片的事件:

 

private final class ButtonClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			ImageThread thread=new ImageThread();
			thread.start();
		}
	}

好了,介绍完毕。

最后如果获取的内容为html页面的内容的话,如果内容过长,就需要用滚动条来显示:

可以在TextView外面加上ScollView加载滚动条:

 <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/htmlcontent"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
        </ScrollView>

 

抱歉!评论已关闭.