zoukankan      html  css  js  c++  java
  • Android读取网络图片

      本文是自己学习所做笔记,欢迎转载,但请注明出处: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>
    








  • 相关阅读:
    【转】JSP三种页面跳转方式
    我要从头做起
    转载:用 Tomcat 和 Eclipse 开发 Web 应用程序
    html的style属性
    Java连接oracle数据库
    tomcat遇到的问题(总结)
    ceshi
    今天要小结一下
    argument.callee.caller.arguments[0]与window.event
    JavaScript事件冒泡简介及应用
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5134431.html
Copyright © 2011-2022 走看看