package com.itheima.netimageviewer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.res.Resources.Theme;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    protected static final int LOAD_IMAGE = 1;
    protected static final int LOAD_ERROR = 2;
    // 服务器所有图片的路径
    private List<String> paths;
    private ImageView iv;
    /**
     * 当前的位置
     */
    private int currentPosition = 0;

    //1.创建一个消息处理器
    private Handler handler = new Handler(){
        //3.处理消息
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case LOAD_IMAGE:
                Bitmap bitmap = (Bitmap) msg.obj;
                iv.setImageBitmap(bitmap);
                break;

            case LOAD_ERROR:
                Toast.makeText(getApplicationContext(), (String)msg.obj, 0).show();
                break;
            }

        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv = (ImageView) findViewById(R.id.iv);
        // 1.连接服务器 获取所有的图片的目录信息
        loadAllImagePath(); 

    }

    /**
     * 开始加载图标,在从服务器获取完毕资源路径之后执行
     */
    private void beginLoadImage() {
        // TODO:把每个图片的路径获取出来, 通过路径加载图片.
        try {
            paths = new ArrayList<String>();
            File file = new File(getCacheDir(), "info.txt");
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String line;
            while ((line = br.readLine()) != null) {
                paths.add(line);
            }
            fis.close();
            // 2.加载图片资源
            loadImageByPath(paths.get(currentPosition));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 通过路径获取图片资源
     *
     * @param path
     *            图片的路径
     * @return
     */
    private void loadImageByPath(final String path) {
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(2000);
                    // 判断缓存是否存在,如果存在就那缓存图片,如果不存在才去获取服务器的资源
                    File file = new File(getCacheDir(), path.replace("/", "")
                            + ".jpg");
                    if (file.exists() && file.length() > 0) {
                        System.out.println("通过缓存把图片资源获取出来....");
                        // 缓存存在
                        //iv.setImageBitmap( BitmapFactory.decodeFile(file.getAbsolutePath()));
                        //2.子线程想去更新ui,发送消息
                        Message msg = Message.obtain();
                        msg.what = LOAD_IMAGE;
                        msg.obj = BitmapFactory.decodeFile(file.getAbsolutePath());
                        handler.sendMessage(msg);
                    } else {
                        System.out.println("通过访问网络把图片资源获取出来....");
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection) url
                                .openConnection();
                        conn.setRequestMethod("GET");
                        int code = conn.getResponseCode();
                        if (code == 200) {
                            InputStream is = conn.getInputStream();
                            // 内存中的图片
                            Bitmap bitmap = BitmapFactory.decodeStream(is);
                            // 如果图片被下载完毕了,应该把图片缓存起来.
                            // CompressFormat.JPEG 压缩的方式 png jpg
                            // 100 压缩比例 100 无损压缩
                            // stream 把图片写入到哪个缓存流里面
                            FileOutputStream stream = new FileOutputStream(file);
                            bitmap.compress(CompressFormat.JPEG, 100, stream);
                            stream.close();
                            is.close();
                            Message msg = Message.obtain();
                            msg.obj = bitmap;
                            msg.what = LOAD_IMAGE;
                            handler.sendMessage(msg);
                            //iv.setImageBitmap(bitmap);
                        } else {
                            //Toast.makeText(MainActivity.this, "获取失败", 0).show();
                            Message msg = Message.obtain();
                            msg.what = LOAD_ERROR;
                            msg.obj = "获取失败";
                            handler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "获取失败", 0).show();
                    Message msg = Message.obtain();
                    msg.what = LOAD_ERROR;
                    msg.obj = "获取失败";
                    handler.sendMessage(msg);
                }
            };
        }.start();
    }

    /**
     * 获取全部图片资源的路径
     */
    private void loadAllImagePath() {
        new Thread() {
            public void run() {
                // 浏览器发送一个get请求就可以把服务器的数据获取出来.
                // 用代码模拟一个http的get请求
                try {
                    // 1.得到服务器资源的路径
                    URL url = new URL("http://192.168.1.109:8080/img/gaga.html");
                    // 2.通过这个路径打开浏览器的连接.
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();// ftp
                                                // http
                                                // https
                                                // rtsp
                    // 3.设置请求方式为get请求
                    conn.setRequestMethod("GET");// 注意get只能用大写 不支持小写
                    // 为了有一个更好的用户ui提醒,获取服务器的返回状态码
                    int code = conn.getResponseCode();// 200 ok 404资源没有找到 503
                                                        // 服务器内部错误
                    if (code == 200) {
                        // 4.获取服务器的返回的流
                        InputStream is = conn.getInputStream();
                        File file = new File(getCacheDir(), "info.txt");
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                        is.close();
                        fos.close();
                        beginLoadImage();
                    } else if (code == 404) {
                        Message msg = Message.obtain();
                        msg.what = LOAD_ERROR;
                        msg.obj = "获取失败,资源没有找到";
                        handler.sendMessage(msg);
                        //Toast.makeText(MainActivity.this, "获取失败,资源没有找到", 0).show();
                    } else {
                        //Toast.makeText(MainActivity.this, "服务器异常", 0).show();
                        Message msg = Message.obtain();
                        msg.what = LOAD_ERROR;
                        msg.obj = "服务器异常";
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //Toast.makeText(MainActivity.this, "获取失败", 0).show();
                    Message msg = Message.obtain();
                    msg.what = LOAD_ERROR;
                    msg.obj = "获取失败";
                    handler.sendMessage(msg);
                }
            };
        }.start();
    }

    /**
     * 上一张
     *
     * @param view
     */
    public void pre(View view) {
        currentPosition--;
        if (currentPosition < 0) {
            currentPosition = paths.size() - 1;
        }
        loadImageByPath(paths.get(currentPosition));

    }

    /**
     * 下一张
     *
     * @param view
     */
    public void next(View view) {
        currentPosition++;
        if (currentPosition == paths.size()) {
            currentPosition = 0;
        }
        loadImageByPath(paths.get(currentPosition));

    }

}

添加权限

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

android网络图片查看器的更多相关文章

  1. Android 网络图片查看器

    今天来实现一下android下的一款简单的网络图片查看器 界面如下: 代码如下: <LinearLayout xmlns:android="http://schemas.android ...

  2. Android -- 网络图片查看器,网络html查看器, 消息机制, 消息队列,线程间通讯

    1. 原理图 2. 示例代码 (网络图片查看器) (1)  HttpURLConnection (2) SmartImageView (开源框架:https://github.com/loopj/an ...

  3. Android 网络图片查看器与网页源码查看器

    在AndroidManifest.xml里面先添加访问网络的权限: <uses-permission android:name="android.permission.INTERNET ...

  4. 无废话Android之内容观察者ContentObserver、获取和保存系统的联系人信息、网络图片查看器、网络html查看器、使用异步框架Android-Async-Http(4)

    1.内容观察者ContentObserver 如果ContentProvider的访问者需要知道ContentProvider中的数据发生了变化,可以在ContentProvider 发生数据变化时调 ...

  5. android 网络_网络图片查看器

    xml <?xml version="1.0"?> -<LinearLayout tools:context=".MainActivity" ...

  6. Android简易实战教程--第二十六话《网络图片查看器在本地缓存》

    本篇接第二十五话  点击打开链接   http://blog.csdn.net/qq_32059827/article/details/52389856 上一篇已经把王略中的图片获取到了.生活中有这么 ...

  7. Android简易实战教程--第二十五话《网络图片查看器》

    访问网络已经有了很成熟的框架.这一篇只是介绍一下HttpURLConnection的简单用法,以及里面的"注意点".这一篇可以复习或者学习HttpURLConnection.han ...

  8. Android项目——网络图片查看器

    效果-=-------------->加入包 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/an ...

  9. Android smartimageview网络图片查看器

    调用代码: SmartImageView siv = (SmartImageView) findViewById(R.id.siv);siv.setImageUrl(et_path.getText() ...

随机推荐

  1. 【Android 复习】:第01期:引导界面(一)ViewPager介绍和使用详解

    一.ViewPager实现的效果图 二.ViewPager实现的功能 看到上面的效果图,想必大家已经猜出了这个类是干吗用的了,ViewPager类提供了多界面切换的新效果, 新效果有如下特征: < ...

  2. IIS6、IIS7和IIS8各版本的差别

    一.写在前面 目前市面上所用的IIS版本估计都是>=6.0的.所以我们主要以下面三个版本进行讲解 服务器版本 IIS默认版本 server2003 6.0 server2008 7.0 serv ...

  3. 1 storm基本概念 + storm编程规范及demo编写

    本博文的主要内容有 .Storm的单机模式安装 .Storm的分布式安装(3节点)   .No space left on device .storm工程的eclipse的java编写 http:// ...

  4. 使用wampserver安装Composer的注意事项

    http://getcomposer.org/Composer-Setup.exe 修改C:\wamp\bin\php\php5.3.10中php.ini中的配置 在php.ini中开启php_ope ...

  5. codeforces 732D

    D. Exams time limit per test 1 second memory limit per test 256 megabytes input standard input outpu ...

  6. java随机数生成(固定位数)

    随机生成 a 到 b (不包含b)的整数: (int)(Math.random()*(b-a))+a; 随机生成 a 到 b (包含b)的整数: (int)(Math.random()*(b-a+1) ...

  7. 如何学会web前端开发

    如何学会web前端开发 http://jingyan.baidu.com/article/b7001fe17623970e7282dd0c.html http://www.yangqq.com/dow ...

  8. List<T>实体去重分组:

    实体去重分组: //实体类 public class Province { public string id { get; set; } public string name { get; set; ...

  9. Java IO流学习总结(转)

    Java流操作有关的类或接口: Java流类图结构: 流的概念和作用 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象.即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输 ...

  10. VS2012执行Cocos2d-xTest案例载入失败解决方式

    编译cocos2d-x,一直提示载入失败 通过搜索,解决方式例如以下: 第一步,通过命令提示行工具进入VS安装文件夹下的%VS2012home%Common7\IDE 第二部,运行devenv.exe ...