zoukankan      html  css  js  c++  java
  • Android 显示网络图片

    本文内容

    • 环境
    • 演示显示网络图片

    本文演示 Android 如何显示网络图片。学习一门新的语言,最好办法就先了解该语言的语法和库,以及设计思想,再着手现实一些常用功能,毕竟以后用该语言是要写程序的,而程序说白了,就是一个个功能点。

    环境


    • Windows 2008 R2 64 位
    • Eclipse ADT V22.6.2,Android 4.4.3
    • 三星 SM-G3508,Android OS 4.1

    演示显示网络图片


    利用一个新线程加载并显示网络图片,并使用 handler 传递消息,若无异常,则用 Toast 现实“加载图片….”,否则,若网络图片不存在,显示“图片不存在”。同时,自定义一个类 HttpUtils,负责用 HTTP 访问网络。Android 程序如下图所示。

    无标题

    图 1

    XML 页面文件略,只是添加 ImageView 和 Button 控件,核心代码如下:

    自定义 HttpUtils 类

    使用 HTTP 协议访问网络图片。

    package com.example.viewwebimagedemo.utils;
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
     
    public class HttpUtils {
     
        private final static String URL_PATH = "http://images.cnblogs.com/cnblogs_com/liuning8023/588559/o_Android.jpg";
     
        public HttpUtils() {
            // TODO Auto-generated constructor stub
        }
     
        public static InputStream getImageViewInputStream() throws IOException {
            InputStream inputStream = null;
     
            URL url = new URL(URL_PATH);
            if (url != null) {
                HttpURLConnection httpURLConnection = (HttpURLConnection) url
                        .openConnection();
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setDoInput(true);
                int response_code = httpURLConnection.getResponseCode();
                if (response_code == 200) {
                    inputStream = httpURLConnection.getInputStream();
                }
            }
            return inputStream;
        }
    }

    MainActivity 类

    负责加载并显示网络图片。

    package com.example.viewwebimagedemo;
     
    import java.io.InputStream;
     
    import com.example.viewwebimagedemo.R;
    import com.example.viewwebimagedemo.utils.HttpUtils;
     
    import android.app.Activity;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Looper;
    import android.os.Message;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
     
    public class MainActivity extends Activity {
        private Button button;
        private ImageView imageView;
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
     
            button = (Button) this.findViewById(R.id.btn);
            imageView = (ImageView) this.findViewById(R.id.imageView);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Thread(access).start();
                }
            });
        }
     
        // 获得图片
        public void getImg() {
            try {
                InputStream inputStream = HttpUtils.getImageViewInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                Looper.prepare();// 必须调用此方法,要不然会报错
                Message msg = new Message();
                msg.what = 0;
                msg.obj = bitmap;
                handler.sendMessage(msg);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "获取图片错误", 1).show();
            }
        }
     
        // 加载图片
        private void setImg(Bitmap bm) {
            imageView.setImageBitmap(bm);
        }
     
        // 另一个线程从网络获得图片
        private Runnable access = new Runnable() {
            @Override
            public void run() {
                getImg();
            }
        };
        // 更新UI信息
        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0) {
                    if (msg.obj == null) {
                        Toast.makeText(getApplicationContext(), "图片不存在", 1).show();
                    } else {
                        Toast.makeText(getApplicationContext(), "加载图片...", 1)
                                .show();
                        setImg((Bitmap) msg.obj);
                    }
                }
            }
        };
    }

    授权 Android 访问网络权限

    修改 AndroidManifest.xml 文件,添加授权 Android 访问网络的权限。

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

    若直接在 Activity 的 onCreate 事件里加载并显示图片,如下所示:

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
     
            // 假设已经从网络获得 bitmap
            imageView = (ImageView) this.findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);
        }

    会报 android.os.NetworkOnMainThreadException 异常。因为,Android 4.x 之后,不允许在主线程进行网络访问。

    下载 Demo

  • 相关阅读:
    如何正确使用 Composer 安装 Laravel 扩展包
    sql之left join、right join、inner join的区别
    mysql decimal类型与decimal长度用法详解
    mysql数据库操作
    linux下如何查看某软件是否已安装
    MySQL数据类型和常用字段属性总结
    mysql数据库字段类型的选择原则
    linux shell 指令 诸如-d, -f, -e之类的判断表达式
    常用的Homebrew命令
    windows下安装php5.5的redis扩展
  • 原文地址:https://www.cnblogs.com/liuning8023/p/3795602.html
Copyright © 2011-2022 走看看