码迷,mamicode.com
首页 > 移动开发 > 详细

Android读取网络图片

时间:2016-01-15 22:40:53      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

  本文是自己学习所做笔记,欢迎转载,但请注明出处:http://blog.csdn.net/jesson20121020  

      在android4.0之后,已不同意在主线程中进行网络请求操作了, 否则会出现NetworkOnMainThreadException异常。

而为了解决在android4.0之上能够进行网络的请求,能够有两种方法来解决,以读取网络的图片为例,先看效果图:

技术分享技术分享

  当点击button时。会将指定地址的网络图片载入在imageVIew中进行显示。

读取网络图片:

  1. 获得指定地址网络图片数据

            有两种方式将指定地址的网络读取到Bitmap中,然后通过imageView载入显示。

    1). 将输入流解码成Bitmap

private static String path = "http://221.203.108.70:8080/jxzy/UploadFiles_4517/201005/2010052615165701.jpg";

public Bitmap getData(){
		Bitmap bitmap = null;
		try {
			URL url = new URL(path);
			URLConnection conn = url.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream(); 
			bitmap = BitmapFactory.decodeStream(is);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitmap;
}
  2). 通过字节数据将输入流写入到输入流中,并通过BitmapFactory.decodeByteArray()方法将其转换成Bitmap

public Bitmap getData1(){
		Bitmap bitmap = null;
		ByteArrayOutputStream bos = null;
		try {
			URL url = new URL(path);
			URLConnection conn = url.openConnection();
			InputStream is = conn.getInputStream();
			bos = new ByteArrayOutputStream();
			byte[] data = new byte[1024];
			int len = 0;
			while((len = is.read(data))!= -1){
				bos.write(data, 0, len);
			}
			byte[] data1 = bos.toByteArray();
			bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, data1.length);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitmap;
}

      

       2. 将得到的Bitmap装载在imageView中显示。

       開始也提到了,在android4.0之上不就不能在主线程中直接进行网络请求等操作了,因此为了将网络图片载入到ImageView中,也有两种方法,详细例如以下:

  方法1:不新建线程。

       直接在onCreate()方法中增加下面两行代码。然后直接在主线程中进行读取网络图片的操作。

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());		   

  有了这两行代码。当然了。这些仅仅适用android4.0之上。你假设targetSDK在4.0之下,也能够不加这两行代码。直接在主线程中进行读取网络图片的操作,可是这样的方法并不推荐。

      接下来就是将第一步两种方法得到Bitmap载入到imageView中,主要代码例如以下:

imageView = (ImageView)findViewById(R.id.imageView);
		
		button = (Button)findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				imageView.setImageBitmap(getData());
			}
		});


      方法2: 利用Thread+Handler

      由于。android也不同意在非UI线程中更新UI,所以不能直接将imageView.setImageBitmap()写在线程中。这就要借助于Handler了,由于Handler是执行在主线程中的,所以在读取网络数据利用Message消息来通知Handler来通知更新UI。主要代码例如以下:

Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			if(msg.what == 1){
				imageView.setImageBitmap(mBitmap);
			}
		};
	};
	Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			msg.what = 1;
			//mBitmap = getData();
			mBitmap = getData1();
			handler.sendMessage(msg);
		}
	};
      接下来,就是在按钮的单击事件中新建一个线程并启动就可以。

button = (Button)findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread(runnable).start();
			}
		});

     最后,给出布局文件,例如以下:

<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/button"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="读取网络图片"
	    />
    <ImageView 
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

</RelativeLayout>








Android读取网络图片

标签:

原文地址:http://www.cnblogs.com/yxwkf/p/5134431.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!